-
Notifications
You must be signed in to change notification settings - Fork 57
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: Automatic token provisioning on deploy #178
Changes from 5 commits
e146e0d
abf9962
36a2684
bc74a24
8b8e288
4d28c6a
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,119 @@ | ||
import { interruptSpinner, wait } from "./spinner.ts"; | ||
import { error } from "../error.ts"; | ||
import { endpoint } from "./api.ts"; | ||
import tokenStorage from "./token_storage.ts"; | ||
|
||
export default { | ||
get: tokenStorage.get, | ||
|
||
async provision() { | ||
// Synchronize provision routine | ||
// to prevent multiple authorization flows from triggering concurrently | ||
this.provisionPromise ??= provision(); | ||
const token = await this.provisionPromise; | ||
this.provisionPromise = null; | ||
return token; | ||
}, | ||
provisionPromise: null as Promise<string> | null, | ||
|
||
revoke: tokenStorage.remove, | ||
}; | ||
|
||
async function provision(): Promise<string> { | ||
const spinnerInterrupted = interruptSpinner(); | ||
wait("").start().info("Provisioning a new access token..."); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Not really sure how spinner exactly works, but what
Is this correct? If correct, then starting the spinner will have essentially no effect because it's immediately stopped and cleared - I wonder if we could just use There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The beauty of it is that the output is consistent with the rest of spinner result messages (the info/warn icon, the identation, etc). There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. (this pattern is used everywhere in deployctl) |
||
const randomBytes = crypto.getRandomValues(new Uint8Array(32)); | ||
const claimVerifier = base64url(randomBytes); | ||
const claimChallenge = base64url(await sha256(claimVerifier)); | ||
|
||
const tokenStream = await fetch( | ||
`${endpoint()}/api/signin/cli/access_token`, | ||
{ method: "POST", body: claimVerifier }, | ||
); | ||
if (!tokenStream.ok) { | ||
error( | ||
`when requesting an access token: ${await tokenStream.statusText}`, | ||
); | ||
} | ||
const url = `${endpoint()}/signin/cli?claim_challenge=${claimChallenge}`; | ||
|
||
wait("").start().info(`Authorization URL: ${url}`); | ||
let openCmd; | ||
// TODO(arnauorriols): use npm:open or deno.land/x/open when either is compatible | ||
switch (Deno.build.os) { | ||
case "darwin": { | ||
openCmd = "open"; | ||
break; | ||
} | ||
case "linux": { | ||
openCmd = "xdg-open"; | ||
break; | ||
} | ||
case "windows": { | ||
openCmd = "start"; | ||
break; | ||
} | ||
} | ||
const open = openCmd !== undefined | ||
? new Deno.Command(openCmd, { | ||
args: [url], | ||
stderr: "piped", | ||
stdout: "piped", | ||
}) | ||
.spawn() | ||
: undefined; | ||
|
||
if (open == undefined) { | ||
const warn = | ||
"Cannot open the authorization URL automatically. Please navigate to it manually using your usual browser"; | ||
wait("").start().info(warn); | ||
} else if (!(await open.status).success) { | ||
const warn = | ||
"Failed to open the authorization URL in your default browser. Please navigate to it manually"; | ||
wait("").start().warn(warn); | ||
if (open !== undefined) { | ||
let error = new TextDecoder().decode((await open.output()).stderr); | ||
const errIndent = 2; | ||
const elipsis = "..."; | ||
const maxErrLength = warn.length - errIndent; | ||
if (error.length > maxErrLength) { | ||
error = error.slice(0, maxErrLength - elipsis.length) + elipsis; | ||
} | ||
// resulting indentation is 1 less than configured | ||
wait({ text: "", indent: errIndent + 1 }).start().fail(error); | ||
} | ||
} | ||
|
||
const spinner = wait("Waiting for authorization...").start(); | ||
|
||
const tokenOrError = await tokenStream.json(); | ||
|
||
if (tokenOrError.error) { | ||
error(`could not provision the access token: ${tokenOrError.error}`); | ||
} | ||
|
||
await tokenStorage.store(tokenOrError.token); | ||
spinner.succeed("Token obtained successfully"); | ||
spinnerInterrupted.resume(); | ||
return tokenOrError.token; | ||
} | ||
|
||
function base64url(binary: Uint8Array): string { | ||
const binaryString = Array.from(binary).map((b) => String.fromCharCode(b)) | ||
.join(""); | ||
const output = btoa(binaryString); | ||
const urlSafeOutput = output | ||
.replaceAll("=", "") | ||
.replaceAll("+", "-") | ||
.replaceAll("/", "_"); | ||
return urlSafeOutput; | ||
} | ||
Comment on lines
+101
to
+110
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Would be good to have a unit test for this There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Any suggestion on test cases I should implement? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Also, is there a way to test it while keeping the function private to the module? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. No, I don't think so. The test should be in a |
||
|
||
async function sha256(random_string: string): Promise<Uint8Array> { | ||
return new Uint8Array( | ||
await crypto.subtle.digest( | ||
"SHA-256", | ||
new TextEncoder().encode(random_string), | ||
), | ||
); | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
import { Spinner, wait as innerWait } from "../../deps.ts"; | ||
|
||
let current: Spinner | null = null; | ||
|
||
export function wait(...params: Parameters<typeof innerWait>) { | ||
current = innerWait(...params); | ||
return current; | ||
} | ||
|
||
export function interruptSpinner(): Interrupt { | ||
current?.stop(); | ||
const interrupt = new Interrupt(current); | ||
current = null; | ||
return interrupt; | ||
} | ||
|
||
export class Interrupt { | ||
#spinner: Spinner | null; | ||
constructor(spinner: Spinner | null) { | ||
this.#spinner = spinner; | ||
} | ||
resume() { | ||
current = this.#spinner; | ||
this.#spinner?.start(); | ||
} | ||
} |
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think this file should be moved to |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
import { interruptSpinner, wait } from "./spinner.ts"; | ||
|
||
interface TokenStorage { | ||
get: () => Promise<string | null>; | ||
store: (token: string) => Promise<void>; | ||
remove: () => Promise<void>; | ||
} | ||
|
||
let defaultMode = false; | ||
|
||
let module: TokenStorage; | ||
if (Deno.build.os === "darwin") { | ||
const darwin = await import("./token_storage/darwin.ts"); | ||
const memory = await import("./token_storage/memory.ts"); | ||
module = { | ||
get: defaultOnError( | ||
"Failed to get token from Keychain", | ||
memory.get, | ||
darwin.getFromKeychain, | ||
), | ||
store: defaultOnError( | ||
"Failed to store token into Keychain", | ||
memory.store, | ||
darwin.storeInKeyChain, | ||
), | ||
remove: defaultOnError( | ||
"Failed to remove token from Keychain", | ||
memory.remove, | ||
darwin.removeFromKeyChain, | ||
), | ||
}; | ||
} else { | ||
module = await import("./token_storage/memory.ts"); | ||
} | ||
export default module; | ||
|
||
function defaultOnError< | ||
// deno-lint-ignore no-explicit-any | ||
F extends (...args: any) => Promise<any>, | ||
>( | ||
notification: string, | ||
defaultFn: (...params: Parameters<F>) => ReturnType<F>, | ||
fn: (...params: Parameters<F>) => ReturnType<F>, | ||
): (...params: Parameters<F>) => ReturnType<F> { | ||
return (...params) => { | ||
if (defaultMode) { | ||
return defaultFn(...params); | ||
} else { | ||
return fn(...params) | ||
.catch((err) => { | ||
const spinnerInterrupt = interruptSpinner(); | ||
wait("").start().warn(notification); | ||
let errStr = err.toString(); | ||
if (errStr.length > 80) { | ||
errStr = errStr.slice(0, 80) + "..."; | ||
} | ||
wait({ text: "", indent: 3 }).start().fail(errStr); | ||
spinnerInterrupt.resume(); | ||
defaultMode = true; | ||
return defaultFn(...params); | ||
}) as ReturnType<F>; | ||
} | ||
}; | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This PR adds auto-provisioning to
deploy
subcommand only, but we'll extend it to other subcommands, right?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes. I can add it in this PR as well
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Added in 4d28c6a
FTR though, #188