Skip to content
Merged
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
60 changes: 60 additions & 0 deletions e2e/testsuite.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ param:
monitorUDP: "{{randAlpha 6}}"
monitorWebsite: "{{randAlpha 6}}"
monitorFTP: "{{randAlpha 6}}"
apiTokenName: "e2e-token-{{randAlpha 6}}"
labelName: "{{randAlpha 3}}"
items:
- name: login
Expand Down Expand Up @@ -69,8 +70,13 @@ items:
- name: missing-auth-header
request:
api: /api/monitors
header:
Accept: application/json
expect:
statusCode: 401
bodyFieldsExpect:
code: 401
msg: Missing Authorization in header
- name: createSitemapMonitor
request:
api: /api/monitor
Expand Down Expand Up @@ -385,6 +391,60 @@ items:
header:
Authorization: Bearer {{.login.data.token}}

## API Token Management
- name: generateApiToken
request:
api: /api/account/token/generate?name={{.apiTokenName}}&expireSeconds=-1
method: POST
header:
Authorization: Bearer {{.login.data.token}}
expect:
bodyFieldsExpect:
code: "0"
- name: listApiTokens
request:
api: /api/account/token
header:
Authorization: Bearer {{.login.data.token}}
expect:
bodyFieldsExpect:
code: "0"
data.0.name: "{{.apiTokenName}}"
data.0.creator: "admin"
- name: listApiTokensByGeneratedToken
request:
api: /api/account/token
header:
Authorization: Bearer {{.generateApiToken.data.token}}
expect:
bodyFieldsExpect:
code: "0"
data.0.name: "{{.apiTokenName}}"
- name: useGeneratedTokenToCallApi
request:
api: /api/monitors?pageIndex=0&pageSize=8
header:
Authorization: Bearer {{.generateApiToken.data.token}}
expect:
bodyFieldsExpect:
code: "0"
- name: deleteApiToken
request:
api: /api/account/token/{{(index .listApiTokens.data 0).id | int64}}
method: DELETE
header:
Authorization: Bearer {{.login.data.token}}
expect:
bodyFieldsExpect:
code: "0"
- name: useRevokedTokenToCallApi
request:
api: /api/monitors?pageIndex=0&pageSize=8
header:
Authorization: Bearer {{.generateApiToken.data.token}}
expect:
statusCode: 401

## Config
- name: getConfigEmail
request:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.apache.hertzbeat.common.entity.manager;

import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import java.time.LocalDateTime;

import static io.swagger.v3.oas.annotations.media.Schema.AccessMode.READ_ONLY;
import static io.swagger.v3.oas.annotations.media.Schema.AccessMode.READ_WRITE;

/**
* API Token Entity - stores generated non-expiring API tokens for management and revocation.
* <p>
* Only "managed" tokens (those generated after this feature was introduced) are stored here.
* Legacy tokens are not tracked and continue to work without DB validation.
* </p>
*/
@Entity
@Table(name = "hzb_auth_token")
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Schema(description = "API Token entity")
@EntityListeners(AuditingEntityListener.class)
public class AuthToken {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Schema(title = "primary id", example = "1", accessMode = READ_ONLY)
private Long id;

@Schema(title = "Token name/description", example = "Alert integration token", accessMode = READ_WRITE)
@Column(length = 255)
private String name;

@Schema(title = "SHA-256 hash of the token value", accessMode = READ_ONLY)
@Column(length = 128, nullable = false, unique = true)
private String tokenHash;

@Schema(title = "Masked token for display", example = "eyJh****xMjM", accessMode = READ_ONLY)
@Column(length = 64)
private String tokenMask;

@Schema(title = "Token status: 0-active", accessMode = READ_ONLY)
@Column(nullable = false)
@Builder.Default
private Byte status = 0;

@Schema(title = "The creator of this token", accessMode = READ_ONLY)
@CreatedBy
private String creator;

@Schema(title = "Token creation time", accessMode = READ_ONLY)
@CreatedDate
private LocalDateTime gmtCreate;

@Schema(title = "Token expiration time, null means never expire", accessMode = READ_ONLY)
private LocalDateTime expireTime;

@Schema(title = "Token last used time", accessMode = READ_ONLY)
private LocalDateTime lastUsedTime;

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.apache.hertzbeat.manager.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
* Registers the managed API token validation interceptor after servlet filters.
*/
@Configuration
public class ApiTokenValidationConfiguration implements WebMvcConfigurer {

private final ApiTokenValidationFilter apiTokenValidationFilter;

public ApiTokenValidationConfiguration(ApiTokenValidationFilter apiTokenValidationFilter) {
this.apiTokenValidationFilter = apiTokenValidationFilter;
}

@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(apiTokenValidationFilter).addPathPatterns("/api/**");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.apache.hertzbeat.manager.config;

import com.usthe.sureness.subject.PrincipalMap;
import com.usthe.sureness.subject.SubjectSum;
import com.usthe.sureness.util.SurenessContextHolder;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;
import org.apache.hertzbeat.collector.dispatch.DispatchConstants;
import org.apache.hertzbeat.common.constants.NetworkConstants;
import org.apache.hertzbeat.common.util.JsonUtil;
import org.apache.hertzbeat.manager.service.AccountService;
import org.apache.hertzbeat.manager.service.impl.AccountServiceImpl;
import org.jspecify.annotations.NonNull;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
* Interceptor to validate that managed API tokens have not been revoked (deleted).
* <p>
* This interceptor runs AFTER the Sureness authentication filter to ensure:
* 1. Only authenticated requests are checked (avoids unnecessary DB hits)
* 2. lastUsedTime is only updated for successfully authenticated requests
* <p>
* Responsibility split:
* - <b>Expiration</b>: handled by Sureness/JWT natively via the {@code exp} claim
* - <b>Revocation</b>: handled here by checking the token's status in the database
* - <b>Last used time</b>: updated here on each valid request (throttled)
* <p>
* Only tokens containing the "managed" claim (generated by the new token management system)
* are validated against the database. Legacy tokens without this claim are allowed to pass
* through for backward compatibility.
* </p>
*/
@Component
@Slf4j
public class ApiTokenValidationFilter implements HandlerInterceptor {

private static final String ROLES_CLAIM = "roles";
private static final String TOKEN_VALIDATION_UNAVAILABLE = "Token validation unavailable";

private final AccountService accountService;

public ApiTokenValidationFilter(AccountService accountService) {
this.accountService = accountService;
}

@Override
public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler)
throws IOException {
SubjectSum subject = SurenessContextHolder.getBindSubject();
if (subject == null || !isManagedToken(subject)) {
return true;
}
String authorization = request.getHeader(NetworkConstants.AUTHORIZATION);

if (authorization != null && authorization.startsWith(DispatchConstants.BEARER)) {
String token = authorization.substring(DispatchConstants.BEARER.length()).trim();
if (!token.isEmpty()) {
try {
String rejectReason = checkManagedToken(subject, token);
if (rejectReason != null) {
return writeError(response, HttpStatus.UNAUTHORIZED, rejectReason);
}
} catch (RuntimeException e) {
log.warn("Managed token validation failed", e);
return writeError(response, HttpStatus.SERVICE_UNAVAILABLE, TOKEN_VALIDATION_UNAVAILABLE);
}
}
}

return true;
}

/**
* Check if a managed token should be rejected.
* <p>
* Returns a rejection reason string if the token should be rejected, null if allowed.
* Checks:
* 1. Only managed tokens (with "managed" claim) are validated — legacy tokens pass through
* 2. Token must exist and be active in the database (not deleted/revoked)
* 3. Token owner must still exist, remain active, and still own the claimed roles
* If the token is valid, updates the last used time.
* </p>
*/
private String checkManagedToken(SubjectSum subject, String token) {
String rejectReason = accountService.checkTokenStatus(token);
if (rejectReason != null) {
return rejectReason;
}
rejectReason = accountService.checkManagedTokenAccess(getCurrentUserId(subject), extractClaimedRoles(subject));
if (rejectReason != null) {
return rejectReason;
}
try {
accountService.touchTokenLastUsedTime(token);
} catch (RuntimeException e) {
log.debug("Failed to update token last used time", e);
}
return null;
}

private boolean isManagedToken(SubjectSum subject) {
PrincipalMap principalMap = subject.getPrincipalMap();
if (principalMap == null) {
return false;
}
Object managed = principalMap.getPrincipal(AccountServiceImpl.CLAIM_MANAGED);
return managed instanceof Boolean ? (Boolean) managed : Boolean.parseBoolean(String.valueOf(managed));
}

@SuppressWarnings("unchecked")
private List<String> extractClaimedRoles(SubjectSum subject) {
Object roles = subject.getRoles();
if (roles instanceof List<?>) {
return (List<String>) roles;
}
PrincipalMap principalMap = subject.getPrincipalMap();
if (principalMap == null) {
return Collections.emptyList();
}
Object claimedRoles = principalMap.getPrincipal(ROLES_CLAIM);
if (claimedRoles instanceof List<?>) {
return (List<String>) claimedRoles;
}
return Collections.emptyList();
}

private String getCurrentUserId(SubjectSum subject) {
Object principal = subject.getPrincipal();
return principal == null ? null : String.valueOf(principal);
}

private boolean writeError(HttpServletResponse response, HttpStatus status, String message) throws IOException {
response.setStatus(status.value());
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json");
try (PrintWriter writer = response.getWriter()) {
writer.write(JsonUtil.toJson(Map.of("code", status.value(), "msg", message)));
}
return false;
}
}
Loading
Loading