Skip to content
Open
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
2 changes: 1 addition & 1 deletion strr-api/poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion strr-api/pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "strr-api"
version = "0.3.46"
version = "0.3.47"
description = ""
authors = ["thorwolpert <thor@wolpert.ca>"]
license = "BSD 3-Clause"
Expand Down Expand Up @@ -38,6 +38,7 @@ nanoid = "^2.0.0"
sql-versioning = { git = "https://github.com/bcgov/sbc-connect-common.git", subdirectory = "python/sql-versioning", branch = "main" }
gcp-queue = { git = "https://github.com/bcgov/sbc-connect-common.git", subdirectory = "python/gcp-queue", branch = "main" }
testcontainers = "^4.14.0"
cachelib = "^0.13.0"

[tool.poetry.group.test.dependencies]
freezegun = "^1.2.2"
Expand Down
59 changes: 45 additions & 14 deletions strr-api/src/strr_api/services/auth_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,12 @@
# POSSIBILITY OF SUCH DAMAGE.
"""Manages Auth service interactions."""

import hashlib
import threading
from http import HTTPStatus

import requests
from cachelib import SimpleCache
from flask import current_app
from requests.exceptions import HTTPError

Expand All @@ -49,6 +52,21 @@
class AuthService:
"""Wrapper service to interact with the Auth API."""

_DEFAULT_TOKEN_TTL = 270
_token_cache = SimpleCache(default_timeout=_DEFAULT_TOKEN_TTL)
_token_lock = threading.Lock()

@staticmethod
def _compute_token_ttl(expires_in) -> int | None:
"""Compute safe cache TTL in seconds, or None if the token should not be cached."""
if expires_in is None:
return AuthService._DEFAULT_TOKEN_TTL
try:
ttl = int(expires_in)
except (TypeError, ValueError):
return None
return ttl - min(30, ttl // 5) if ttl > 0 else None

@classmethod
def get_service_client_token(
cls,
Expand All @@ -67,27 +85,40 @@ def get_service_client_token(
if timeout is None:
timeout = int(current_app.config.get("AUTH_SVC_TIMEOUT", 20))

data = "grant_type=client_credentials"
cache_key = hashlib.sha256(f"{client_id}:{client_secret}:{token_url}".encode()).hexdigest()
if cached_token := cls._token_cache.get(cache_key):
return cached_token

# get service account token
res = requests.post(
url=token_url,
data=data,
headers={"content-type": "application/x-www-form-urlencoded"},
auth=(client_id, client_secret),
timeout=timeout,
)
with cls._token_lock:
if cached_token := cls._token_cache.get(cache_key):
return cached_token

try:
return res.json().get("access_token")
except Exception:
return None
res = requests.post(
url=token_url,
data="grant_type=client_credentials",
headers={"content-type": "application/x-www-form-urlencoded"},
auth=(client_id, client_secret),
timeout=timeout,
)

try:
token_data = res.json()
access_token = token_data.get("access_token")
except Exception:
return None

if not access_token:
return None

if ttl := cls._compute_token_ttl(token_data.get("expires_in")):
cls._token_cache.set(cache_key, access_token, timeout=ttl)

return access_token

@classmethod
def search_accounts(cls, account_name: str):
"""Searches for an existing account."""
token = AuthService.get_service_client_token()
print(token)
endpoint = f"{current_app.config.get('AUTH_SVC_URL')}/orgs?name={account_name.strip()}"
accounts = RestService.get(endpoint=endpoint, token=token).json()
return accounts
Expand Down
84 changes: 84 additions & 0 deletions strr-api/tests/unit/services/test_auth_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
# you may not use this file except in compliance with the License.
"""Tests for AuthService (HTTP/RestService mocked)."""

import threading
import time
from http import HTTPStatus
from unittest.mock import MagicMock, patch

Expand All @@ -14,6 +16,14 @@
from strr_api.services.auth_service import AuthService


@pytest.fixture(autouse=True)
def clear_token_cache():
"""Ensure service client token cache is isolated per test."""
AuthService._token_cache.clear()
yield
AuthService._token_cache.clear()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Clever way to clear before and after each test 👍

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Feel free to resolve this conversation, haha.



@patch("strr_api.services.auth_service.requests.post")
def test_get_service_client_token_success(mock_post, app_ctx):
mock_post.return_value.json.return_value = {"access_token": "tok"}
Expand All @@ -23,6 +33,80 @@ def test_get_service_client_token_success(mock_post, app_ctx):
assert token == "tok"


@patch("strr_api.services.auth_service.requests.post")
def test_get_service_client_token_caches_within_ttl(mock_post, app_ctx):
mock_post.return_value.json.return_value = {"access_token": "cached-tok", "expires_in": 300}

first = AuthService.get_service_client_token("id", "sec", "https://token")
second = AuthService.get_service_client_token("id", "sec", "https://token")

assert first == "cached-tok"
assert second == "cached-tok"
mock_post.assert_called_once()


@patch("strr_api.services.auth_service.requests.post")
def test_get_service_client_token_refreshes_near_expiry(mock_post, app_ctx):
mock_post.side_effect = [
MagicMock(json=MagicMock(return_value={"access_token": "tok-1", "expires_in": 300})),
MagicMock(json=MagicMock(return_value={"access_token": "tok-2", "expires_in": 300})),
]
now = [1000.0]

with patch("cachelib.simple.time", side_effect=lambda: now[0]):
first = AuthService.get_service_client_token("id", "sec", "https://token")
now[0] = 1275.0 # past 300 - 30 = 270s cached TTL
second = AuthService.get_service_client_token("id", "sec", "https://token")

assert first == "tok-1"
assert second == "tok-2"
assert mock_post.call_count == 2


@patch("strr_api.services.auth_service.requests.post")
def test_get_service_client_token_does_not_cache_zero_ttl(mock_post, app_ctx):
mock_post.return_value.json.return_value = {"access_token": "ephemeral", "expires_in": 0}

AuthService.get_service_client_token("id", "sec", "https://token")
AuthService.get_service_client_token("id", "sec", "https://token")

assert mock_post.call_count == 2


@patch("strr_api.services.auth_service.requests.post")
def test_get_service_client_token_invalid_expires_in_still_returns_token(mock_post, app_ctx):
mock_post.return_value.json.return_value = {"access_token": "tok-raw", "expires_in": ""}

first = AuthService.get_service_client_token("id", "sec", "https://token")
second = AuthService.get_service_client_token("id", "sec", "https://token")

assert first == "tok-raw"
assert second == "tok-raw"
assert mock_post.call_count == 2


@patch("strr_api.services.auth_service.requests.post")
def test_get_service_client_token_coalesces_concurrent_fetches(mock_post, app_ctx):
def slow_post(*_args, **_kwargs):
time.sleep(0.05)
return MagicMock(json=MagicMock(return_value={"access_token": "shared-tok", "expires_in": 300}))

mock_post.side_effect = slow_post
results: list[str] = []

def worker():
results.append(AuthService.get_service_client_token("id", "sec", "https://token", timeout=5))

threads = [threading.Thread(target=worker) for _ in range(5)]
for t in threads:
t.start()
for t in threads:
t.join()

assert results == ["shared-tok"] * 5
mock_post.assert_called_once()


@patch("strr_api.services.auth_service.requests.post")
def test_get_service_client_token_json_failure_returns_none(mock_post, app_ctx):
mock_post.return_value.json.side_effect = ValueError("bad json")
Expand Down
111 changes: 87 additions & 24 deletions strr-host-pm-web/app/pages/auth/account/create-new.vue
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,72 @@ const state = reactive({

const createAccountFormRef = ref<Form<CreateAccountSchema>>()

const MIN_ACCOUNT_NAME_SEARCH_LENGTH = 3
const ACCOUNT_NAME_DEBOUNCE_MS = 450
let debounceTimer: ReturnType<typeof setTimeout> | null = null
let accountSearchAbortController: AbortController | null = null

function cancelPendingAccountNameSearch () {
if (debounceTimer !== null) {
clearTimeout(debounceTimer)
debounceTimer = null
}
if (accountSearchAbortController) {
accountSearchAbortController.abort()
accountSearchAbortController = null
}
}

function isAbortError (err: unknown): boolean {
if (!(err instanceof Error)) {
return false
}
return err.name === 'AbortError' || (err as { cause?: { name?: string } }).cause?.name === 'AbortError'
}

async function checkAccountNameExists (trimmedName: string): Promise<boolean> {
cancelPendingAccountNameSearch()
const controller = new AbortController()
accountSearchAbortController = controller

try {
loadingCheckAccountName.value = true
// also returns limit: number, orgs: Array<any>, page: number, but we only need the total here
const { total } = await $strrApi<{ total: number }>('/accounts/search', { // TODO: move function to store/composable?
params: { name: trimmedName },
signal: controller.signal
})
if (controller.signal.aborted) {
return false
}
accountExists.value = total > 0
return true
} catch (e) {
if (controller.signal.aborted || isAbortError(e)) {
return false
}
logFetchError(e, 'Error checking if account name exists')
accountExists.value = true // assume account exists if api error
return true
} finally {
if (accountSearchAbortController === controller) {
accountSearchAbortController = null
loadingCheckAccountName.value = false
}
}
}

async function handleCreateAccount () {
try {
loadingSubmitForm.value = true
const trimmedName = state.accountName.trim()
if (trimmedName.length < MIN_ACCOUNT_NAME_SEARCH_LENGTH || loadingCheckAccountName.value) {
const completed = await checkAccountNameExists(trimmedName)
if (!completed || accountExists.value || state.accountName.trim() !== trimmedName) {
createAccountFormRef.value?.validate('accountName', { silent: true })
return
}
}
const response = await $strrApi<{sbc_account_id: number, user_id: number}>('/accounts', { // TODO: move function to store/composable?
method: 'POST',
body: {
Expand All @@ -60,33 +123,33 @@ async function handleCreateAccount () {
}
}

// validate account name already exists
watchDebounced(
() => state.accountName,
async (newVal) => {
if (newVal.trim() !== '') {
try {
loadingCheckAccountName.value = true
// also returns limit: number, orgs: Array<any>, page: number, but we only need the total here
const { total } = await $strrApi<{ total: number }>('/accounts/search', { // TODO: move function to store/composable?
params: { name: newVal }
})
accountExists.value = total > 0
} catch (e) {
logFetchError(e, 'Error checking if account name exists')
accountExists.value = true // assume account exists if api error
} finally {
loadingCheckAccountName.value = false
}
} else {
accountExists.value = false // set to false if accountName is empty
// Validate account name existence on trimmed changes, keeping Save disabled while a search is pending
watch(
() => state.accountName.trim(),
(trimmedName) => {
cancelPendingAccountNameSearch()
accountExists.value = false

if (trimmedName.length < MIN_ACCOUNT_NAME_SEARCH_LENGTH) {
Comment thread
severinbeauvais marked this conversation as resolved.
Resolved
loadingCheckAccountName.value = false
createAccountFormRef.value?.validate('accountName', { silent: true })
return
}
// revalidate input after accountExists ref is updated
createAccountFormRef.value?.validate('accountName', { silent: true })
},
{ debounce: 150 } // short debounce to get the 'on input' real time validation, this may need to be tweaked

loadingCheckAccountName.value = true
debounceTimer = setTimeout(async () => {
debounceTimer = null
if (await checkAccountNameExists(trimmedName)) {
createAccountFormRef.value?.validate('accountName', { silent: true })
}
}, ACCOUNT_NAME_DEBOUNCE_MS)
}
)

onScopeDispose(() => {
cancelPendingAccountNameSearch()
})

useHead({
title: t('page.createAccount.title')
})
Expand Down
2 changes: 1 addition & 1 deletion strr-host-pm-web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "strr-host-pm-web",
"private": true,
"type": "module",
"version": "1.3.38",
"version": "1.3.39",

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#1939 and #1943 also bump host to 1.3.39, so whichever merges later will need another bump

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Feel free to resolve this conversation if you're not concerned about this.

"engines": {
"node": ">=24"
},
Expand Down
Loading
Loading