Skip to content
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

Tools: rewrite gen-edgehog-jwt in Elixir instead of Python #738

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions doc/pages/admin/deploying_with_kubernetes.md
Original file line number Diff line number Diff line change
Expand Up @@ -786,10 +786,10 @@ At this point your Edgehog instance is ready to use. The last step is generating
your Edgehog frontend instance. You can do so using the `gen-edgehog-jwt` tool contained in the
`tools` directory of the [Edgehog
repo](https://github.com/edgehog-device-manager/edgehog/tree/main/tools).
The tool requires Elixir in your system, which you can install with `asdf install` using the [asdf](https://asdf-vm.com/) version manager.

```bash
$ pip3 install pyjwt
$ ./gen-edgehog-jwt -t tenant -k <PATH-TO-TENANT-PRIVATE-KEY>
$ ./tools/gen-edgehog-jwt -t tenant -k <PATH-TO-TENANT-PRIVATE-KEY>
```

Values to be replaced
Expand Down
26 changes: 5 additions & 21 deletions doc/pages/tutorials/edgehog_in_5_minutes.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,39 +104,23 @@ This will create the tenant `acme-inc` and add a sample device to it.
Nice! Now we have our tenant but we can't access to it yet, we need a token.
Luckily Edgehog includes a scripts to generate one!

First you'll need to make sure to have python version 3 installed.
First you'll need to make sure to have Elixir installed in your system.
If you're using the [asdf](https://asdf-vm.com/) version manager, you can install Elixir by running:

```sh
$ python3 --version
Python 3.x.y
```

> While not mandatory, it is advised to use a python virtual environment to make sure your
> globally installed python packages don't mess with this script's dependencies and vice versa.
> Doing this is pretty straightforward, but you may need to install the `python3-venv` package if
> you are using a Debian/Ubuntu-based system.
>
> ```sh
> $ python3 -m venv pyenv
> $ source pyenv/bin/activate
> ```

Then, navigate to the `tools/` subdirectory and install the required dependencies

```sh
$ cd tools && pip install -r requirements.txt
$ asdf install
```

Now you can generate the login token with

```sh
$ ./gen-edgehog-jwt -t tenant -k ../acme_private.pem
$ ./tools/gen-edgehog-jwt -t tenant -k ./acme_private.pem
```

> If in the previous section you had decided not to use a custom key, use this command instead
>
> ```sh
> $ ./gen-edgehog-jwt -t tenant -k ../backend/priv/repo/seeds/keys/tenant_private.pem
> $ ./tools/gen-edgehog-jwt -t tenant -k ./backend/priv/repo/seeds/keys/tenant_private.pem
> ```

You can finally navigate to `http://edgehog.localhost` in your browser and login to the
Expand Down
130 changes: 90 additions & 40 deletions tools/gen-edgehog-jwt
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#!/usr/bin/env python3
#!/usr/bin/env elixir
#
# This file is part of Edgehog.
#
Expand All @@ -19,42 +19,92 @@
# SPDX-License-Identifier: Apache-2.0
#

import argparse
import datetime
import jwt

default_claim_payload = "*"

if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Generate a valid JWT for Edgehog")
parser.add_argument("-k", "--private-key", type=str, required=True, help="Path to the private key file for signing "\
"the Authorization token.")
parser.add_argument("-e", "--expiry", type=int, required=False, default=86400, help="Expiry of the token in seconds. "\
"If 0, the token never expires. Defaults to 24 hours.")
parser.add_argument("-t", "--token-type", required=True, choices=["tenant", "admin"], help="The type of token to "\
"generate. `tenant` generates a token for the Tenant GraphQL API, `admin` generates a token for the Admin REST API.")
args = parser.parse_args()
args_map = vars(args)

with open(args_map["private_key"], "r") as pk:
private_key_pem = pk.read()

now = datetime.datetime.utcnow()
claims = {"iat": now}
if args_map["token_type"] == "tenant":
# Currently claims can have any payload, we just pass "*"
claims["e_tga"] = default_claim_payload
else:
# Currently claims can have any payload, we just pass "*"
claims["e_ara"] = default_claim_payload
expiry = args_map["expiry"]
if expiry > 0:
claims["exp"] = now + datetime.timedelta(seconds=expiry)

algo = None
if "-----BEGIN RSA PRIVATE KEY-----" in private_key_pem:
algo = "RS256"
elif "-----BEGIN EC PRIVATE KEY-----" in private_key_pem:
algo = "ES256"

print(jwt.encode(claims, private_key_pem, algorithm=algo))
Mix.install([
{:jason, "~> 1.4"},
{:jose, "~> 1.11"}
])

defmodule JwtGenerator do
@moduledoc """
Generate a valid JWT for Edgehog
"""

@default_claim_payload "*"

def main(args) do
options = parse_args(args)

private_key_pem = File.read!(options[:private_key])
now = DateTime.utc_now()
claims = generate_claims(options[:token_type], options[:expiry], now)

algo =
cond do
String.contains?(private_key_pem, "-----BEGIN RSA PRIVATE KEY-----") -> "RS256"
String.contains?(private_key_pem, "-----BEGIN EC PRIVATE KEY-----") -> "ES256"
true -> raise "Unsupported private key format"
end

jwt = sign_token(claims, private_key_pem, algo)
IO.puts(jwt)
end

defp parse_args(args) do
{parsed, _, _} =
OptionParser.parse(args,
switches: [
private_key: :string,
expiry: :integer,
token_type: :string
],
aliases: [k: :private_key, e: :expiry, t: :token_type]
)

parsed_map = Enum.into(parsed, %{})

cond do
is_nil(parsed_map[:private_key]) ->
raise ArgumentError, "Private key is required. Use -k or --private-key to specify the key."

is_nil(parsed_map[:token_type]) ->
raise ArgumentError, "Token type is required. Use -t or --token-type to specify 'tenant' or 'admin'."

true ->
Map.put_new(parsed_map, :expiry, 86_400)
end
end

defp generate_claims("tenant", expiry, now) do
claims = %{"iat" => DateTime.to_unix(now), "e_tga" => @default_claim_payload}
add_expiry(claims, expiry, now)
end

defp generate_claims("admin", expiry, now) do
claims = %{"iat" => DateTime.to_unix(now), "e_ara" => @default_claim_payload}
add_expiry(claims, expiry, now)
end

defp generate_claims(_, _, _) do
raise ArgumentError, "Invalid token type. Must be 'tenant' or 'admin'."
end

defp add_expiry(claims, expiry, now) when expiry > 0 do
Map.put(claims, "exp", DateTime.to_unix(DateTime.add(now, expiry)))
end

defp add_expiry(claims, _, _) do
claims
end

defp sign_token(claims, private_key, algo) do
jwk = JOSE.JWK.from_pem(private_key)

headers = %{"alg" => algo}

{_, jwt} = JOSE.JWT.sign(jwk, headers, claims) |> JOSE.JWS.compact()

jwt
end
end

JwtGenerator.main(System.argv())
22 changes: 0 additions & 22 deletions tools/requirements.txt

This file was deleted.