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

[PLATFORM-474]: [Auth0Ex] Make observability of cache set errors better #87

Merged
Show file tree
Hide file tree
Changes from 5 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
24 changes: 21 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,14 @@ An easy to use library to authenticate machine-to-machine communications through

Supports both retrieval of JWTs and their verification and validation.

## Table of contents

- [Installation](#installation)
- [Configuration](#configuration)
- [I am a DevOps, what do I have to do?](#i-am-a-devops-what-do-i-have-to-do)
- [Usage](#usage)
- [Development](#development)

## Installation

The package can be installed by adding `prima_auth0_ex` to your list of dependencies in `mix.exs`:
Expand All @@ -22,11 +30,11 @@ def deps do
end
```

### Configuration
## Configuration

`prima_auth0_ex` can be configured to be used for an API consumer, an API provider or both.

#### API Consumer
### API Consumer

To configure the library for use from a client (ie. a service that needs to obtain tokens to access some API),
the following configuration is supported:
Expand Down Expand Up @@ -55,7 +63,7 @@ Otherwise, the JWTs generated by Auth0 may not include the necessary permissions

A visualization of the logic behind the `TokenProvider` is available [here](client_flow.jpg).

#### API Provider
### API Provider

To configure the library for use from a server (ie. a service that exposes an API),
the following configuration is supported:
Expand Down Expand Up @@ -83,6 +91,16 @@ config :prima_auth0_ex, :server,
missing_auth_header_log_level: :warn
```

### I am a DevOps, what do I have to do?

As a DevOps someone is probably going to ask you to generate a `cache_encryption_key`, which can be generated either running `mix keygen` or using the following snippet:

```elixir
:crypto.strong_rand_bytes(32) |> Base.encode64()
```

> :warning: **The token needs to be 32 bytes long AND base64 encoded**, failing to do so will result in tokens not getting cached on Redis. :warning:

## Usage

### Obtaining tokens
Expand Down
6 changes: 6 additions & 0 deletions config/config.exs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@ config :prima_auth0_ex, :server,
issuer: "https://tenant.eu.auth0.com/",
first_jwks_fetch_sync: true

config :statix, PrimaAuth0Ex.Statix,
enabled: false,
host: "statsd",
prefix: "prima_auth0_ex",
tags: ["env:#{config_env()}"]

config :logger, :console, metadata: :all

config :logger, level: :info
Expand Down
4 changes: 4 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,7 @@ services:
hostname: 'redis'
environment:
- ALLOW_EMPTY_PASSWORD=yes
statsd:
image: mendhak/udp-listener:latest
environment:
UDPPORT: 8125
2 changes: 2 additions & 0 deletions lib/prima_auth0_ex/application.ex
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ defmodule PrimaAuth0Ex.Application do
alias PrimaAuth0Ex.{JwksStrategy, TokenProvider}

def start(_type, _args) do
:ok = PrimaAuth0Ex.Statix.connect()

log_configuration_errors()

children = client_children() ++ cache_children() ++ server_children()
Expand Down
5 changes: 5 additions & 0 deletions lib/prima_auth0_ex/statix.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
defmodule PrimaAuth0Ex.Statix do
@moduledoc nil

use Statix, runtime_config: true
end
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ defmodule PrimaAuth0Ex.TokenProvider.Auth0AuthorizationService do
@behaviour PrimaAuth0Ex.TokenProvider.AuthorizationService

require Logger
alias PrimaAuth0Ex.Statix
alias PrimaAuth0Ex.TokenProvider.TokenInfo

@auth0_token_api_path "/oauth/token"
Expand All @@ -15,6 +16,7 @@ defmodule PrimaAuth0Ex.TokenProvider.Auth0AuthorizationService do
request_body = body(credentials, audience)
url = credentials.base_url <> @auth0_token_api_path

Statix.increment("new_token", 1, tags: ["audience:#{audience}"])
Logger.info("Requesting token to Auth0", audience: audience, url: url)

url
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,13 @@ defmodule PrimaAuth0Ex.TokenProvider.EncryptedRedisTokenCache do

defp do_set_token_for(audience, token) do
with {:ok, json_token} <- to_json(token),
{:ok, encrypted} <- TokenEncryptor.encrypt(json_token),
do: save(encrypted, key_for(audience), token.expires_at)
{:ok, encrypted} <- TokenEncryptor.encrypt(json_token) do
save(encrypted, key_for(audience), token.expires_at)
else
{:error, reason} ->
Logger.warn("Error encrypting token.", audience: audience, reason: inspect(reason))
{:error, reason}
end
end

defp key_for(audience), do: "prima_auth0_ex_tokens:#{namespace()}:#{audience}"
Expand Down
6 changes: 5 additions & 1 deletion mix.exs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@ defmodule PrimaAuth0Ex.MixProject do
{:plug, "~> 1.10", optional: true},
{:redix, "~> 0.9 or ~> 1.0"},
{:telepoison, "~> 1.0"},
{:timex, "~> 3.6"}
{:timex, "~> 3.6"},
{:statix, github: "primait/statix", branch: "feature/switch_from_config"}
] ++ dev_deps()
end

Expand All @@ -64,6 +65,9 @@ defmodule PrimaAuth0Ex.MixProject do
"format --check-formatted",
"credo -a --strict",
"dialyzer"
],
keygen: [
"run --no-start -e ':crypto.strong_rand_bytes(32) |> Base.encode64() |> IO.puts()'"
]
]
end
Expand Down
1 change: 1 addition & 0 deletions mix.lock
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
"ranch": {:hex, :ranch, "1.8.0", "8c7a100a139fd57f17327b6413e4167ac559fbc04ca7448e9be9057311597a1d", [:make, :rebar3], [], "hexpm", "49fbcfd3682fab1f5d109351b61257676da1a2fdbe295904176d5e521a2ddfe5"},
"redix": {:hex, :redix, "1.1.5", "6fc460d66a5c2287e83e6d73dddc8d527ff59cb4d4f298b41e03a4db8c3b2bd5", [:mix], [{:castore, "~> 0.1.0", [hex: :castore, repo: "hexpm", optional: true]}, {:telemetry, "~> 0.4.0 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "679afdd4c14502fe9c11387ff1cdcb33065a1cf511097da1eee407f17c7a418b"},
"ssl_verify_fun": {:hex, :ssl_verify_fun, "1.1.6", "cf344f5692c82d2cd7554f5ec8fd961548d4fd09e7d22f5b62482e5aeaebd4b0", [:make, :mix, :rebar3], [], "hexpm", "bdb0d2471f453c88ff3908e7686f86f9be327d065cc1ec16fa4540197ea04680"},
"statix": {:git, "https://github.com/primait/statix.git", "3f3b093f5583e0317fa03cef8c7989414c78a0d7", [branch: "feature/switch_from_config"]},
"stream_data": {:hex, :stream_data, "0.5.0", "b27641e58941685c75b353577dc602c9d2c12292dd84babf506c2033cd97893e", [:mix], [], "hexpm", "012bd2eec069ada4db3411f9115ccafa38540a3c78c4c0349f151fc761b9e271"},
"telemetry": {:hex, :telemetry, "1.1.0", "a589817034a27eab11144ad24d5c0f9fab1f58173274b1e9bae7074af9cbee51", [:rebar3], [], "hexpm", "b727b2a1f75614774cff2d7565b64d0dfa5bd52ba517f16543e6fc7efcc0df48"},
"telepoison": {:hex, :telepoison, "1.0.0", "3ccc7bc065360521b95aca6f7151246b064545ac3dca5db30d98865a451560c7", [:mix], [{:httpoison, "~> 1.6", [hex: :httpoison, repo: "hexpm", optional: false]}, {:opentelemetry_api, "~> 1.0", [hex: :opentelemetry_api, repo: "hexpm", optional: false]}], "hexpm", "9691886b19d8ebf99432c4914d148a27c11c149c3ce8144bfa4ec56b43ed374e"},
Expand Down
30 changes: 30 additions & 0 deletions test/integration/encrypted_redis_token_cache_test.exs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
defmodule Integration.TokenProvider.EncryptedRedisTokenCacheTest do
use ExUnit.Case, async: true

import ExUnit.CaptureLog
import PrimaAuth0Ex.TestSupport.TimeUtils
alias PrimaAuth0Ex.TokenProvider.{EncryptedRedisTokenCache, TokenInfo}

Expand All @@ -14,6 +15,35 @@ defmodule Integration.TokenProvider.EncryptedRedisTokenCacheTest do
:ok
end

describe "logs on token encryption failure while setting token" do
test "malformed token" do
log =
capture_log(fn ->
EncryptedRedisTokenCache.set_token_for(@test_audience, <<0x80>>)
end)

assert String.match?(log, ~r/reason=/)
assert String.match?(log, ~r/audience=redis-integration-test-audience/)
assert String.match?(log, ~r/Error encrypting token./)
end

test "wrong cache_encryption_key" do
env_to_restore = Application.fetch_env!(:prima_auth0_ex, :client)
Application.put_env(:prima_auth0_ex, :client, Keyword.put(env_to_restore, :cache_encryption_key, "abcd"))

log =
capture_log(fn ->
EncryptedRedisTokenCache.set_token_for(@test_audience, sample_token())
end)

assert String.match?(log, ~r/reason=/)
assert String.match?(log, ~r/audience=redis-integration-test-audience/)
assert String.match?(log, ~r/Error encrypting token./)

Application.put_env(:prima_auth0_ex, :client, env_to_restore)
end
end

test "persists and retrieves tokens" do
token = sample_token()
:ok = EncryptedRedisTokenCache.set_token_for(@test_audience, token)
Expand Down