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

STEP-7 Code coverage added. #7

Open
wants to merge 17 commits into
base: main
Choose a base branch
from
Open

STEP-7 Code coverage added. #7

wants to merge 17 commits into from

Conversation

ekhvalov
Copy link
Owner

No description provided.

@MysterySuperhero MysterySuperhero self-assigned this Feb 5, 2024
Copy link
Collaborator

@MysterySuperhero MysterySuperhero left a comment

Choose a reason for hiding this comment

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

  1. Граф зависимостей – гуд.
  2. Схемы и их визуализация – гуд. В идеале опоясать их текстовыми пояснениями по моментам, описанным задании про документацию. Иначе полноценной документацией это назвать нельзя
  3. Приседания с jwt показались половинчатыми, как будто оставили работу на пол пути. Стоит доработать, или явно пояснить почему оставили в таком состоянии и к чему стремились.

2 из 3 норм – лайк. На Stepik также засчитываем модуль.

@@ -47,14 +46,12 @@ func (a access) HasRole(name string) bool {
return false
}

// Valid returns errors:
// Validate checks validity of the claims (will be called by jwt-go library parser).
// possible errors:
// - from StandardClaims validation;
Copy link
Collaborator

Choose a reason for hiding this comment

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

Комментарий к методу не соответствует действительности 🙂 Ошибок от StandardClaims больше нет

Copy link
Owner Author

Choose a reason for hiding this comment

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

Исправил

)

type claims struct {
jwt.StandardClaims
Aud keycloakclient.Audition `json:"aud"`
Copy link
Collaborator

Choose a reason for hiding this comment

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

Можно теперь спилить и пользоваться зеркальным полем из jwt.RegisteredClaims. У нас была специфическая нужда выделить отдельное поле из jwt.StandardClaims, т.к. там aud строго строка

Copy link
Owner Author

Choose a reason for hiding this comment

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

Исправил

)

type claims struct {
jwt.StandardClaims
Aud keycloakclient.Audition `json:"aud"`
AuthTime int64 `json:"auth_time"`
Copy link
Collaborator

Choose a reason for hiding this comment

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

Раз уж начали глядеть сюда, то зачем вам это поле? Вроде, не используется 🙂

Copy link
Owner Author

Choose a reason for hiding this comment

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

Удалил

}, nil
}

// q: write documentation
Copy link
Collaborator

Choose a reason for hiding this comment

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

Академический интерес: что значит q:?

Copy link
Owner Author

Choose a reason for hiding this comment

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

Артифакт от общения с GitHub Copilot :)

issuer string `option:"mandatory" validate:"required"`
}

func NewJWTParser(opts JWTParserOptions) (*JWTParser, error) {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Ловко вышло, но:

  1. Если переезжаем на что-то вместо, то старое хорошо бы спиливать. Не у дел остался код из keycloakclient. Ради этого же была затея с переездом? 🙂
  2. Парсеру не место, кмк, в пакете с миддлварями. Возможно, стоит его запихнуть в тот же пакет, где лежит бывший клиент keycloak.

image

Copy link
Owner Author

Choose a reason for hiding this comment

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

В keycloakclient ещё есть код авторизации, который используется в тестах, так что удалил только то, что связано с интроспекцией токена.
Парсер перенёс в пакет internaljwt.

# C4 model architecture diagrams

## System Context
<details>
Copy link
Collaborator

Choose a reason for hiding this comment

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

Не знал, как в MD-формате делать раскрывающиеся списки. Лайк 🙂

Taskfile.yml Outdated
@@ -8,6 +8,7 @@ vars:
docker-compose.yml
docker-compose.sentry.yml
docker-compose.swagger-ui.yml
docker-compose.structurizr.yml
Copy link
Collaborator

Choose a reason for hiding this comment

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

Опечатка у вас, нет такого файла 🙂

Copy link
Owner Author

Choose a reason for hiding this comment

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

Исправил.

# https://docs.structurizr.com/dsl/basics#basics
# To see diagrams:
# 1. Run dependencies COMPOSE_PROFILES=structurizr-ui task deps
# 2. Open http://localhost:8070
Copy link
Collaborator

Choose a reason for hiding this comment

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

Прикольная штука – лайк 👍

Академический интерес: используете ли в работе? Поделитесь, пожалуйста, юзкейсами.

Copy link
Owner Author

Choose a reason for hiding this comment

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

Пока только в этом проекте использовал.

@@ -23,3 +25,11 @@ func TestParseAndValidate(t *testing.T) {
require.NoError(t, err)
assert.NotEmpty(t, cfg.Log.Level)
}

func TestParseAndValidateWithEnv(t *testing.T) {
assert.NoError(t, os.Setenv(fmt.Sprintf("%s_LOG_LEVEL", config.EnvPrefix), "debug"))
Copy link
Collaborator

Choose a reason for hiding this comment

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

Тут, скорее, нужен require

Copy link
Owner Author

Choose a reason for hiding this comment

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

Исправил.

@@ -23,3 +25,11 @@ func TestParseAndValidate(t *testing.T) {
require.NoError(t, err)
assert.NotEmpty(t, cfg.Log.Level)
}

func TestParseAndValidateWithEnv(t *testing.T) {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Скорее, это тест на переопределение ENV-переменной значения из конфига 🙂

Copy link
Owner Author

Choose a reason for hiding this comment

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

Переименовал тест.

Task commands to run Swagger and Structurizr ui added.
JWT parser moved to package 'internaljwt'.
Copy link
Collaborator

@MysterySuperhero MysterySuperhero left a comment

Choose a reason for hiding this comment

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

По-прежнему лайк. Стало гораздо чище 🫡

BasePath string `fig:"base_path" validate:"required,url"`
Realm string `fig:"realm" validate:"required"`
ClientID string `fig:"client_id" validate:"required"`
ClientSecret string `fig:"client_secret" validate:"required"`
Copy link
Collaborator

Choose a reason for hiding this comment

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

Вы правы, я сам это упустил это при ревью. Лайк 👍

}
if err := c.Valid(); err != nil {
return false, err
// var ve *jwt.ValidationError
Copy link
Collaborator

Choose a reason for hiding this comment

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

А тут какую цель преследовали, пытаясь анализировать содержимое ошибки? 🙂

Судя по тому, что тесты проходят в keycloak_token_auth_test.go, ошибки из keycloak_claims.go стали прозрачно возвращаться -> можно спилить закоментированный код

Copy link
Collaborator

Choose a reason for hiding this comment

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

Похожие артефакты как будто в func (s *KeycloakTokenAuthSuite) TestInvalidIssuer() {

authMdlwr echo.MiddlewareFunc
req *http.Request
resp *httptest.ResponseRecorder
ctx echo.Context
}

func (s *KeycloakTokenAuthSuite) SetupTest() {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Лайк за адаптацию теста 🫡

}
token, c, err := parseTokenAndClaims(tokenStr)
tokenStr := extractToken(auth, secWsProtocol)
// if result, err := introspector.IntrospectToken(eCtx.Request().Context(), tokenStr); err != nil {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Почти, осталось чуть-чуть подчистить, кмк 🙂

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants