|
root / src / commands / key.reef
key.reef Reef 485 lines 13.5 KB
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
/******************************************************************************
               __               ____                __
              / /   ___  ____ _/ __/_____________ _/ /__
             / /   / _ \/ __ `/ /_/ ___/ ___/ __ `/ / _ \
            / /___/  __/ /_/ / __(__  ) /__/ /_/ / /  __/
           /_____/\___/\__,_/_/ /____/\___/\__,_/_/\___/

   (C)opyright 2025, Leafscale, LLC -  https://www.leafscale.com

   Project: Zygaena
  Filename: key.reef
   Authors: Chris Tusa <chris.tusa@leafscale.com>
   License: <see LICENSE file included with this source code>
Description: Key command - manage signing keys

******************************************************************************/

module commands.key

import sys.args
import sys.process
import io.file
import io.dir
import core.str
import core.signing
import util.color
import exitcodes as ec
import core.result as res

export
    fn execute(): int
end export

fn execute(): int
    let argc = args.count()

    if argc < 3
        print_usage()
        return ec.EXIT_USAGE()
    end if

    let subcommand = args.get(2)

    if subcommand == "list"
        list_keys()
        return ec.EXIT_SUCCESS()
    elif subcommand == "generate"
        if argc < 4
            color.print_error("Missing key name")
            println("Usage: coral key generate <name>")
            return ec.EXIT_USAGE()
        end if
        generate_key(args.get(3))
        return ec.EXIT_SUCCESS()
    elif subcommand == "import"
        if argc < 4
            color.print_error("Missing key file")
            println("Usage: coral key import <file> [name]")
            return ec.EXIT_USAGE()
        end if
        let key_file = args.get(3)
        mut name = ""
        if argc >= 5
            name = args.get(4)
        end if
        import_key(key_file, name)
        return ec.EXIT_SUCCESS()
    elif subcommand == "export"
        if argc < 4
            color.print_error("Missing key name")
            println("Usage: coral key export <name>")
            return ec.EXIT_USAGE()
        end if
        export_key(args.get(3))
        return ec.EXIT_SUCCESS()
    elif subcommand == "delete"
        if argc < 4
            color.print_error("Missing key name")
            println("Usage: coral key delete <name>")
            return ec.EXIT_USAGE()
        end if
        delete_key(args.get(3))
        return ec.EXIT_SUCCESS()
    elif subcommand == "init"
        init_keyring()
        return ec.EXIT_SUCCESS()
    elif subcommand == "trust"
        if argc < 4
            color.print_error("Missing key name")
            println("Usage: coral key trust <name>")
            return ec.EXIT_USAGE()
        end if
        trust_key(args.get(3))
        return ec.EXIT_SUCCESS()
    elif subcommand == "revoke"
        if argc < 4
            color.print_error("Missing key name")
            println("Usage: coral key revoke <name>")
            return ec.EXIT_USAGE()
        end if
        revoke_key(args.get(3))
        return ec.EXIT_SUCCESS()
    else
        color.print_error("Unknown subcommand: " + subcommand)
        print_usage()
        return ec.EXIT_USAGE()
    end if
end execute

proc list_keys()
    color.print_action("Signing keys:")
    println("")

    mut keys: [signing.KeyPair] = new [signing.KeyPair](64)
    let count = signing.list_keys(keys, 64)

    if count == 0
        color.print_info("No keys found")
        println("")
        color.print_info("Generate a key with: coral key generate <name>")
        return
    end if

    mut i = 0
    while i < count
        let key = keys[i]
        print("  ")
        print(key.name)
        if str.length(key.private_key) > 0
            print(" [private+public]")
        else
            print(" [public only]")
        end if
        if key.trusted
            print(" [trusted]")
        end if
        println("")
        i = i + 1
    end while

    println("")
    color.print_info("Total: " + int_to_str(count) + " key(s)")
end list_keys

proc generate_key(name: string)
    color.print_action("Generating Ed25519 keypair: " + name)

    let result = signing.generate_keypair(name)

    if result.success
        color.print_success("Keypair generated successfully")
        println("")
        color.print_info("Private key: " + signing.get_keyring_dir() + "/" + name + ".key")
        color.print_info("Public key:  " + signing.get_keyring_dir() + "/" + name + ".pub")
    else
        color.print_error(result.error)
    end if
end generate_key

proc import_key(key_file: string, name: string)
    if not file.fileExists(key_file)
        color.print_error("Key file not found: " + key_file)
        return
    end if

    // Determine name from filename if not provided
    mut key_name = name
    if str.length(key_name) == 0
        key_name = extract_name(key_file)
    end if

    if str.length(key_name) == 0
        color.print_error("Could not determine key name. Please specify one.")
        return
    end if

    color.print_action("Importing key: " + key_name)

    let key_data = res.unwrap_or(file.readFile(key_file), "")
    let result = signing.import_key(key_data, key_name)

    if result.success
        color.print_success("Key imported successfully")
    else
        color.print_error(result.error)
    end if
end import_key

proc export_key(name: string)
    let keyring = signing.get_keyring_dir()
    let pub_path = keyring + "/" + name + ".pub"

    if not file.fileExists(pub_path)
        color.print_error("Key not found: " + name)
        return
    end if

    color.print_action("Public key for " + name + ":")
    println("")

    let key_data = res.unwrap_or(file.readFile(pub_path), "")
    println(key_data)
end export_key

proc delete_key(name: string)
    let keyring = signing.get_keyring_dir()

    // Check if key exists
    let pub_path = keyring + "/" + name + ".pub"
    let priv_path = keyring + "/" + name + ".key"

    if not file.fileExists(pub_path) and not file.fileExists(priv_path)
        color.print_error("Key not found: " + name)
        return
    end if

    // Ask for confirmation if private key exists
    if file.fileExists(priv_path)
        color.print_warning("This will delete the private key! Are you sure?")
        color.print_info("Use --force to confirm deletion")

        if not args.has_flag("force")
            return
        end if
    end if

    // Delete files
    if file.fileExists(pub_path)
        let cmd1 = "rm -f \"" + pub_path + "\""
        let pid1 = process.process_spawn_shell(cmd1)
        if pid1 > 0
            process.process_wait(pid1)
        end if
    end if

    if file.fileExists(priv_path)
        let cmd2 = "rm -f \"" + priv_path + "\""
        let pid2 = process.process_spawn_shell(cmd2)
        if pid2 > 0
            process.process_wait(pid2)
        end if
    end if

    color.print_success("Deleted key: " + name)
end delete_key

fn extract_name(path: string): string
    // Extract filename without extension
    let len = str.length(path)
    if len == 0
        return ""
    end if

    // Find last slash
    mut start = 0
    mut i = 0
    while i < len
        if path[i] == '/'
            start = i + 1
        end if
        i = i + 1
    end while

    // Find last dot
    mut end_pos = len
    i = len - 1
    while i >= start
        if path[i] == '.'
            end_pos = i
        end if
        i = i - 1
    end while

    if end_pos <= start
        return str.substring(path, start, len - start)
    end if

    return str.substring(path, start, end_pos - start)
end extract_name

// Initialize the keyring directory structure
proc init_keyring()
    color.print_action("Initializing keyring...")

    let keyring = signing.get_keyring_dir()
    let trusted_keys_dir = "/var/lib/coral/trusted-keys"

    // Create keyring directory
    if not dir.dir_exists(keyring)
        if not res.is_ok(dir.create_dir_all(keyring))
            color.print_error("Failed to create keyring directory: " + keyring)
            return
        end if
        color.print_info("Created: " + keyring)
    else
        color.print_info("Keyring already exists: " + keyring)
    end if

    // Create trusted-keys directory
    if not dir.dir_exists(trusted_keys_dir)
        if not res.is_ok(dir.create_dir_all(trusted_keys_dir))
            color.print_error("Failed to create trusted-keys directory")
            return
        end if
        color.print_info("Created: " + trusted_keys_dir)
    else
        color.print_info("Trusted keys directory already exists: " + trusted_keys_dir)
    end if

    // Set permissions (keyring should be root-only for private keys)
    let cmd = "chmod 700 \"" + keyring + "\""
    let pid = process.process_spawn_shell(cmd)
    if pid > 0
        process.process_wait(pid)
    end if

    color.print_success("Keyring initialized")
    color.print_info("Generate keys with: coral key generate <name>")
end init_keyring

// Add a key to the trusted keys list
proc trust_key(name: string)
    let keyring = signing.get_keyring_dir()
    let trusted_dir = "/var/lib/coral/trusted-keys"
    let pub_path = keyring + "/" + name + ".pub"

    // Check if key exists
    if not file.fileExists(pub_path)
        color.print_error("Key not found: " + name)
        color.print_info("Import or generate the key first")
        return
    end if

    // Ensure trusted-keys directory exists
    if not dir.dir_exists(trusted_dir)
        if not res.is_ok(dir.create_dir_all(trusted_dir))
            color.print_error("Failed to create trusted-keys directory")
            return
        end if
    end if

    // Check if already trusted
    let trusted_path = trusted_dir + "/" + name + ".pub"
    if file.fileExists(trusted_path)
        color.print_warning("Key already trusted: " + name)
        return
    end if

    // Copy public key to trusted directory
    let cmd = "cp \"" + pub_path + "\" \"" + trusted_path + "\""
    let pid = process.process_spawn_shell(cmd)
    if pid < 0
        color.print_error("Failed to copy key")
        return
    end if

    let exit_code = process.process_wait(pid)
    if exit_code != 0
        color.print_error("Failed to trust key")
        return
    end if

    color.print_success("Trusted key: " + name)
    color.print_info("Packages signed with this key will now be accepted")
end trust_key

// Remove a key from the trusted keys list
proc revoke_key(name: string)
    let trusted_dir = "/var/lib/coral/trusted-keys"
    let trusted_path = trusted_dir + "/" + name + ".pub"

    // Check if key is trusted
    if not file.fileExists(trusted_path)
        color.print_error("Key is not in trusted list: " + name)
        return
    end if

    // Confirm revocation
    if not args.has_flag("force") and not args.has_flag("yes")
        color.print_warning("This will revoke trust for key: " + name)
        color.print_info("Use --force or -y to confirm")
        return
    end if

    // Remove from trusted keys
    let cmd = "rm -f \"" + trusted_path + "\""
    let pid = process.process_spawn_shell(cmd)
    if pid < 0
        color.print_error("Failed to revoke key")
        return
    end if

    let exit_code = process.process_wait(pid)
    if exit_code != 0
        color.print_error("Failed to remove key from trusted list")
        return
    end if

    color.print_success("Revoked trust for key: " + name)
    color.print_info("Packages signed with this key will no longer be accepted")
end revoke_key

// List trusted keys
proc list_trusted_keys()
    let trusted_dir = "/var/lib/coral/trusted-keys"

    if not dir.dir_exists(trusted_dir)
        color.print_info("No trusted keys (directory does not exist)")
        return
    end if

    let entries = res.unwrap_or(dir.list_dir(trusted_dir), new [string](0))
    let count = entries.length()

    if count == 0
        color.print_info("No trusted keys")
        return
    end if

    println("")
    color.print_action("Trusted keys:")
    mut i = 0
    while i < count
        let entry = entries[i]
        if str.ends_with(entry, ".pub")
            let name = str.substring(entry, 0, str.length(entry) - 4)
            println("  " + name)
        end if
        i = i + 1
    end while
end list_trusted_keys

proc print_usage()
    println("Usage: coral key <command> [options]")
    println("")
    println("Manage signing keys for package verification.")
    println("")
    println("Commands:")
    println("  list                List all keys in keyring")
    println("  generate <name>     Generate a new Ed25519 keypair")
    println("  import <file> [name] Import a public key")
    println("  export <name>       Export a public key")
    println("  delete <name>       Delete a key (use --force for private keys)")
    println("")
    println("Trust management:")
    println("  init                Initialize keyring directories")
    println("  trust <name>        Add key to trusted list")
    println("  revoke <name>       Remove key from trusted list")
    println("")
    println("Examples:")
    println("  coral key init")
    println("  coral key generate maintainer")
    println("  coral key import repo.pub community")
    println("  coral key trust community")
end print_usage

// Helper: convert int to string
fn int_to_str(n: int): string
    if n == 0
        return "0"
    end if

    mut negative = false
    mut value = n
    if n < 0
        negative = true
        value = 0 - n
    end if

    mut result = ""
    while value > 0
        let digit = value % 10
        result = str.concat(str.substring("0123456789", digit, 1), result)
        value = value / 10
    end while

    if negative
        result = str.concat("-", result)
    end if

    return result
end int_to_str

end module