syndicate-nim/src/syndicate/capabilities.nim

47 lines
1.4 KiB
Nim
Raw Normal View History

2021-09-21 14:39:15 +00:00
# SPDX-FileCopyrightText: ☭ 2021 Emery Hemingway
# SPDX-License-Identifier: Unlicense
import preserves
2021-10-27 16:54:20 +00:00
import ./protocols/sturdy, ./private/hmacs
2021-09-07 10:01:42 +00:00
export `$`
2022-12-08 08:15:01 +00:00
proc mint*[T](key: openarray[byte]; oid: Preserve[T]): SturdyRef[T] =
SturdyRef[T](oid: oid, sig: hmacSha256(key, encode(oid), key.len))
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)
SturdyRef[E](oid: oidPr, sig: hmacSha256(key, encode(oidPr), key.len))
2021-10-27 16:54:20 +00:00
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,
sig: hmacSha256(r.sig, caveats.encode))
result.caveatChain.add caveats
2022-12-08 08:15:01 +00:00
proc validate*[T](key: openarray[byte]; r: SturdyRef[T]): bool =
2021-09-07 10:01:42 +00:00
var sig = hmacSha256(key, r.oid.encode, key.len)
for a in r.caveatChain:
sig = hmacSha256(sig, a.encode)
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)