Osy#betaRun it on Osyrin: osyrin.com

Reference / Function

A key pair for a test — Crypto.NewRsaKeyPair

Crypto.NewRsaKeyPair(bits: int) → RsaKeyPair · keys.PublicKeyPem → string · keys.PrivateKey → RsaPrivateKey · Crypto.SignRs256(privateKey: RsaPrivateKey, data: byte[]) → byte[] · Secret.X.Stub(privateKey) · Secret.X.StubFor(id, privateKey)

Make an RSA key pair inside a test, so code that signs (a JWT for a GitHub App, a Snowflake or Google service account) can be tested without a private key committed anywhere. The public half is PEM text; the private half signs, can be a secret's value for the test, and never leaves memory.

stable3 examples compiled by CIfunctioncryptosigningjwt

Summary#

Signing code needs a private key to run, and a test has none: a real key must not be committed, and a fake one that does not parse makes Crypto.SignRs256 throw. Crypto.NewRsaKeyPair(2048) makes a real key pair in memory, for the length of the test. The test signs with the private half, or hands it to the secret the code under test reads, and then checks the signature with the public half, exactly as the service on the other end would.

The private half never leaves memory. It cannot become text, be logged, be stored, be written to a file, be returned or be sent anywhere. The compiler refuses each of those, and anything it cannot see is refused when the test runs.

Signature#

var keys = Crypto.NewRsaKeyPair(bits: int);          // 2048, 3072 or 4096 — test code only

keys.PublicKeyPem                                    // string: "-----BEGIN PUBLIC KEY-----…"
keys.PrivateKey                                      // the private half: it signs, and nothing else

Crypto.SignRs256(keys.PrivateKey, data: byte[])      // → byte[], RS256 (RSASSA-PKCS1-v1_5 + SHA-256)
Secret.<Name>.Stub(keys.PrivateKey);                 // the secret's value for the rest of the test
Secret.<Keyed>.StubFor(id, keys.PrivateKey);         // one id of a keyed secret, for the rest of the test

Description#

It is for test code. Crypto.NewRsaKeyPair compiles in a [Test], a [TestFixture] and any function in a .test.osy file, and runs only when a test runs. Anywhere else it is GENERATED_KEY_TEST_ONLY: an app's real key is issued by the service that trusts it, given to a declared secret with osy secret set AppKey --file key.pem, and signed with through Crypto.SignRs256(Secret.AppKey, data) (Asymmetric signing — Crypto.SignRs256, VerifyRs256, SignEs256, VerifyEs256).

Hold it in a var. The pair and its private half have no type name to write, so no field, parameter or return type can carry one. Hold the pair in a local, and read its two members where you need them:

MemberTypeWhat it is for
keys.PublicKeyPemstringThe public half as a PEM. Give it to Crypto.VerifyRs256, compare it, store it, send it: it is public.
keys.PrivateKeythe private halfSigns. Pass it to Crypto.SignRs256, or to a secret for the test.

The private half goes to three places, and the compiler refuses every other. It may be held in a local, signed with (Crypto.SignRs256(keys.PrivateKey, data)), and given to a secret for the test (Secret.X.Stub(…) or Secret.X.StubFor(id, …)). Every other use is GENERATED_KEY_ESCAPES: interpolation, + with a string, ToString(), Convert.ToString, a log line, JsonSerializer.Serialize, an object's or entity's field, a list, a function argument, a return value, a tuple, a lambda's result, a file, a request, an exception, and an assertion's operand (a failing assertion prints its operands). A Func or Action lambda may not capture it either, even one that only signs with it: a function value carries what it captures wherever it goes. Sign in the test's own body, or stub the secret and let the code under test sign. A stub's own lambda is the exception, because it stays in the test's stub table: a fake service may sign its answer with Http.Get.Stub((url, headers) => new HttpResponse { StatusCode = 200, Body = Convert.ToBase64String(Crypto.SignRs256(keys.PrivateKey, Text.ToBytes(url))) }). The list is closed on purpose. A place that is not on it is refused, including one that is added to the language later.

Give it to the code under test through its secret. The code you are testing reads its key from a secret (Crypto.SignRs256(Secret.AppKey, …)), and that is the code the test should run. Secret.AppKey.Stub(keys.PrivateKey) makes that read answer the generated key for the rest of the test, in the test body and in every server call the test causes. For a keyed secret, Secret.X.StubFor(id, keys.PrivateKey) does the same for one id. Secret.X.IsSetFor(id) answers true while the key is held, Secret.X.SetIds() lists the id, and Secret.X.RetireFor(id) lets it go. The key is held in memory only. It is never written to the secret store, so it is never encrypted, kept or listed by osy secret. A text value for a keyed secret goes through the door instead, as in the app: Secret.X.SetFor(id, "test-value").

A package's tests app stubs the package's keyed secret the same way. When the keyed secret is declared by a package the app composes and grants (use Acme.GitHub { secret "GitHubAppKey"; }), a test of the app may still write Secret.GitHubAppKey.StubFor(id, keys.PrivateKey) or Secret.GitHubAppKey.SetFor(id, "test-value"), and the package's own code reads that id's value. Only these test verbs are allowed, and only in test code. The app's own code still cannot name the package's secret.

At run time, it refuses to become text. The code under test reads a stubbed secret as a string, so the compiler cannot follow the key into it. If that code puts the key into text ("Bearer " + Secret.AppKey), logs it, writes it to JSON or holds it across a suspension (a browser call or a workflow wait), the test fails with GENERATED_KEY_LEFT_MEMORY. The message never contains the key, because there is no text of the key anywhere in the process. A trace or osy inspect shows a local holding one as unreadable.

Every call makes a fresh key. Make the pair once, at the top of the test or in a [TestFixture], and use that pair. 2048 bits is what GitHub Apps, Google service accounts and Snowflake issue; 3072 and 4096 are accepted and are slower to make. Any other size is refused.

Examples#

The code under test reads its key from a secret. The test stubs that secret with a generated key and checks the signature with the public half:

app.Secrets = [
  new Secret("AppKey"),
  new Secret("InstallKey") { Keyed = true, MayWrite = MayManageInstallKey }
];

policy MayManageInstallKey(string id) => true;

string B64Url(byte[] b) {
  return Convert.ToBase64String(b).Replace("+", "-").Replace("/", "_").Replace("=", "");
}

// The code under test: it signs with the app's key, read from its secret.
string SignedToken(string subject) {
  var signingInput = B64Url(Text.ToBytes("{\"alg\":\"RS256\"}")) + "." + B64Url(Text.ToBytes("{\"sub\":\"" + subject + "\"}"));
  return signingInput + "." + B64Url(Crypto.SignRs256(Secret.AppKey, Text.ToBytes(signingInput)));
}

[Test]
void the_token_verifies_with_the_public_half() {
  var keys = Crypto.NewRsaKeyPair(2048);
  Secret.AppKey.Stub(keys.PrivateKey);

  var parts = SignedToken("ada").Split(".");
  var signature = parts[2].Replace("-", "+").Replace("_", "/");
  while (signature.Length % 4 != 0) { signature = signature + "="; }
  Assert.True(Crypto.VerifyRs256(keys.PublicKeyPem, Text.ToBytes(parts[0] + "." + parts[1]),
    Convert.FromBase64String(signature)));
}

The same for one id of a keyed secret, and the test signing directly:

string SignFor(string id, string data) {
  return Convert.ToBase64String(Crypto.SignRs256(Secret.InstallKey.For(id), Text.ToBytes(data)));
}

[Test]
void one_installation_signs_with_its_held_key() {
  var keys = Crypto.NewRsaKeyPair(2048);
  Secret.InstallKey.StubFor("install-1", keys.PrivateKey);
  Assert.True(Secret.InstallKey.IsSetFor("install-1"));

  var signature = Convert.FromBase64String(SignFor("install-1", "hello"));
  Assert.True(Crypto.VerifyRs256(keys.PublicKeyPem, Text.ToBytes("hello"), signature));

  var direct = Crypto.SignRs256(keys.PrivateKey, Text.ToBytes("hello"));
  Assert.True(Crypto.VerifyRs256(keys.PublicKeyPem, Text.ToBytes("hello"), direct));

  Assert.True(Secret.InstallKey.RetireFor("install-1"));
  Assert.False(Secret.InstallKey.IsSetFor("install-1"));
}

Code under test that puts the key into text fails the test with GENERATED_KEY_LEFT_MEMORY, and the message carries no part of the key:

string BearerHeader() {
  return "Bearer " + Secret.AppKey;
}

[Test]
void the_key_never_becomes_a_header() {
  var keys = Crypto.NewRsaKeyPair(2048);
  Secret.AppKey.Stub(keys.PrivateKey);
  var fault = Assert.Throws<Exception>(() => BearerHeader());
  Assert.StartsWith("GENERATED_KEY_LEFT_MEMORY", fault.Message);
}

See also#

Related

Asymmetric signing — Crypto.SignRs256, VerifyRs256, SignEs256, VerifyEs256

Sign with a private key, verify with a public one. This is what a signed JWT is made of, and a signed JWT is how almost…

Outbound calls in a test

A `[Test]` answers an outbound call from a stub — `Http.<Verb>.Stub(url => …)` — or, when the test says so with…

reading a secret's value (Secret.Name)

`Secret.Name` in a function body evaluates to the declared secret's value — the key itself, as a string, read at the…