syndicate-nim/src/syndicate/capabilities.nim

58 lines
1.6 KiB
Nim
Raw Normal View History

2023-05-03 17:10:33 +00:00
# SPDX-FileCopyrightText: ☭ Emery Hemingway
2021-09-21 14:39:15 +00:00
# SPDX-License-Identifier: Unlicense
2023-05-03 17:10:33 +00:00
from std/sequtils import toSeq
import hashlib/misc/blake2
2021-09-21 14:39:15 +00:00
import preserves
2023-05-03 17:10:33 +00:00
import ./protocols/sturdy
2023-04-10 21:56:51 +00:00
from ./actors import Ref
2021-09-07 10:01:42 +00:00
export `$`
2023-05-03 17:10:33 +00:00
proc hmac(key, data: openarray[byte]): seq[byte] =
count[Hmac[BLAKE2S_256]](key, data).data[0..15].toSeq
2022-12-08 08:15:01 +00:00
proc mint*[T](key: openarray[byte]; oid: Preserve[T]): SturdyRef[T] =
2023-05-03 17:10:33 +00:00
SturdyRef[T](oid: oid, sig: hmac(key, encode oid))
2021-10-27 16:54:20 +00:00
2022-12-08 08:15:01 +00:00
proc mint*[T](key: openarray[byte]; oid: T; E = void): SturdyRef[E] =
var oidPr = toPreserve(oid, E)
2023-05-03 17:10:33 +00:00
SturdyRef[E](oid: oidPr, sig: hmac(key, encode oidPr))
2021-10-27 16:54:20 +00:00
2023-04-10 21:56:51 +00:00
proc mint*(): SturdyRef[Ref] =
var key: array[16, byte]
cast[SturdyRef[Ref]](mint(key, "syndicate", Ref))
2022-12-08 08:15:01 +00:00
proc attenuate*[T](r: SturdyRef[T]; caveats: Attenuation): SturdyRef[T] =
result = SturdyRef[T](
2021-09-07 10:01:42 +00:00
oid: r.oid,
caveatChain: r.caveatChain,
2023-05-03 17:10:33 +00:00
sig: hmac(r.sig, encode caveats))
2021-09-07 10:01:42 +00:00
result.caveatChain.add caveats
2022-12-08 08:15:01 +00:00
proc validate*[T](key: openarray[byte]; r: SturdyRef[T]): bool =
2023-05-03 17:10:33 +00:00
var sig = hmac(key, encode r.oid)
2021-09-07 10:01:42 +00:00
for a in r.caveatChain:
2023-05-03 17:10:33 +00:00
sig = hmac(sig, encode a)
2021-09-07 10:01:42 +00:00
r.sig == sig
when isMainModule:
from os import commandLineParams
var key: array[16, byte]
case readBytes(stdin, key, 0, 16)
of 16: discard
of 0: stderr.writeLine "using null key"
else: quit "expected sixteen bytes of key from stdin"
var oids: seq[Preserve[void]]
for p in commandLineParams():
add(oids, parsePreserves p)
if oids.len == 0: oids.add(toPreserve "syndicate")
for oid in oids:
let sturdy = mint(key, oid)
doAssert validate(key, sturdy)
stdout.writeLine(sturdy)