JAVA SCA
Last updated on

Description
JAVA SCA
CVE-2009-387X
src/share/classes/java/security/MessageDigest.java
package java.security;
import java.util.*;
import java.lang.*;
import java.io.IOException;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.io.InputStream;
import java.io.ByteArrayInputStream;
import java.nio.ByteBuffer;
/**
* This MessageDigest class provides applications the functionality of a
* message digest algorithm, such as MD5 or SHA.
* Message digests are secure one-way hash functions that take arbitrary-sized
* data and output a fixed-length hash value.
*
* <p>A MessageDigest object starts out initialized. The data is
* processed through it using the {@link #update(byte) update}
* methods. At any point {@link #reset() reset} can be called
* to reset the digest. Once all the data to be updated has been
* updated, one of the {@link #digest() digest} methods should
* be called to complete the hash computation.
*
* <p>The <code>digest</code> method can be called once for a given number
* of updates. After <code>digest</code> has been called, the MessageDigest
* object is reset to its initialized state.
*
* <p>Implementations are free to implement the Cloneable interface.
* Client applications can test cloneability by attempting cloning
* and catching the CloneNotSupportedException: <p>
*
* <pre>
* MessageDigest md = MessageDigest.getInstance("SHA");
*
* try {
* md.update(toChapter1);
* MessageDigest tc1 = md.clone();
* byte[] toChapter1Digest = tc1.digest();
* md.update(toChapter2);
* ...etc.
* } catch (CloneNotSupportedException cnse) {
* throw new DigestException("couldn't make digest of partial content");
* }
* </pre>
*
* <p>Note that if a given implementation is not cloneable, it is
* still possible to compute intermediate digests by instantiating
* several instances, if the number of digests is known in advance.
*
* <p>Note that this class is abstract and extends from
* <code>MessageDigestSpi</code> for historical reasons.
* Application developers should only take notice of the methods defined in
* this <code>MessageDigest</code> class; all the methods in
* the superclass are intended for cryptographic service providers who wish to
* supply their own implementations of message digest algorithms.
*
* @author Benjamin Renaud
*
*
* @see DigestInputStream
* @see DigestOutputStream
*/
public abstract class MessageDigest extends MessageDigestSpi {
private String algorithm;
// The state of this digest
private static final int INITIAL = 0;
private static final int IN_PROGRESS = 1;
private int state = INITIAL;
// The provider
private Provider provider;
/**
* Creates a message digest with the specified algorithm name.
*
* @param algorithm the standard name of the digest algorithm.
* See Appendix A in the <a href=
* "../../../technotes/guides/security/crypto/CryptoSpec.html#AppA">
* Java Cryptography Architecture API Specification & Reference </a>
* for information about standard algorithm names.
*/
protected MessageDigest(String algorithm) {
this.algorithm = algorithm;
}
/**
* Returns a MessageDigest object that implements the specified digest
* algorithm.
*
* <p> This method traverses the list of registered security Providers,
* starting with the most preferred Provider.
* A new MessageDigest object encapsulating the
* MessageDigestSpi implementation from the first
* Provider that supports the specified algorithm is returned.
*
* <p> Note that the list of registered providers may be retrieved via
* the {@link Security#getProviders() Security.getProviders()} method.
*
* @param algorithm the name of the algorithm requested.
* See Appendix A in the <a href=
* "../../../technotes/guides/security/crypto/CryptoSpec.html#AppA">
* Java Cryptography Architecture API Specification & Reference </a>
* for information about standard algorithm names.
*
* @return a Message Digest object that implements the specified algorithm.
*
* @exception NoSuchAlgorithmException if no Provider supports a
* MessageDigestSpi implementation for the
* specified algorithm.
*
* @see Provider
*/
public static MessageDigest getInstance(String algorithm)
throws NoSuchAlgorithmException {
try {
Object[] objs = Security.getImpl(algorithm, "MessageDigest",
(String)null);
if (objs[0] instanceof MessageDigest) {
MessageDigest md = (MessageDigest)objs[0];
md.provider = (Provider)objs[1];
return md;
} else {
MessageDigest delegate =
new Delegate((MessageDigestSpi)objs[0], algorithm);
delegate.provider = (Provider)objs[1];
return delegate;
}
} catch(NoSuchProviderException e) {
throw new NoSuchAlgorithmException(algorithm + " not found");
}
}
/**
* Returns a MessageDigest object that implements the specified digest
* algorithm.
*
* <p> A new MessageDigest object encapsulating the
* MessageDigestSpi implementation from the specified provider
* is returned. The specified provider must be registered
* in the security provider list.
*
* <p> Note that the list of registered providers may be retrieved via
* the {@link Security#getProviders() Security.getProviders()} method.
*
* @param algorithm the name of the algorithm requested.
* See Appendix A in the <a href=
* "../../../technotes/guides/security/crypto/CryptoSpec.html#AppA">
* Java Cryptography Architecture API Specification & Reference </a>
* for information about standard algorithm names.
*
* @param provider the name of the provider.
*
* @return a MessageDigest object that implements the specified algorithm.
*
* @exception NoSuchAlgorithmException if a MessageDigestSpi
* implementation for the specified algorithm is not
* available from the specified provider.
*
* @exception NoSuchProviderException if the specified provider is not
* registered in the security provider list.
*
* @exception IllegalArgumentException if the provider name is null
* or empty.
*
* @see Provider
*/
public static MessageDigest getInstance(String algorithm, String provider)
throws NoSuchAlgorithmException, NoSuchProviderException
{
if (provider == null || provider.length() == 0)
throw new IllegalArgumentException("missing provider");
Object[] objs = Security.getImpl(algorithm, "MessageDigest", provider);
if (objs[0] instanceof MessageDigest) {
MessageDigest md = (MessageDigest)objs[0];
md.provider = (Provider)objs[1];
return md;
} else {
MessageDigest delegate =
new Delegate((MessageDigestSpi)objs[0], algorithm);
delegate.provider = (Provider)objs[1];
return delegate;
}
}
/**
* Returns a MessageDigest object that implements the specified digest
* algorithm.
*
* <p> A new MessageDigest object encapsulating the
* MessageDigestSpi implementation from the specified Provider
* object is returned. Note that the specified Provider object
* does not have to be registered in the provider list.
*
* @param algorithm the name of the algorithm requested.
* See Appendix A in the <a href=
* "../../../technotes/guides/security/crypto/CryptoSpec.html#AppA">
* Java Cryptography Architecture API Specification & Reference </a>
* for information about standard algorithm names.
*
* @param provider the provider.
*
* @return a MessageDigest object that implements the specified algorithm.
*
* @exception NoSuchAlgorithmException if a MessageDigestSpi
* implementation for the specified algorithm is not available
* from the specified Provider object.
*
* @exception IllegalArgumentException if the specified provider is null.
*
* @see Provider
*
* @since 1.4
*/
public static MessageDigest getInstance(String algorithm,
Provider provider)
throws NoSuchAlgorithmException
{
if (provider == null)
throw new IllegalArgumentException("missing provider");
Object[] objs = Security.getImpl(algorithm, "MessageDigest", provider);
if (objs[0] instanceof MessageDigest) {
MessageDigest md = (MessageDigest)objs[0];
md.provider = (Provider)objs[1];
return md;
} else {
MessageDigest delegate =
new Delegate((MessageDigestSpi)objs[0], algorithm);
delegate.provider = (Provider)objs[1];
return delegate;
}
}
/**
* Returns the provider of this message digest object.
*
* @return the provider of this message digest object
*/
public final Provider getProvider() {
return this.provider;
}
/**
* Updates the digest using the specified byte.
*
* @param input the byte with which to update the digest.
*/
public void update(byte input) {
engineUpdate(input);
state = IN_PROGRESS;
}
/**
* Updates the digest using the specified array of bytes, starting
* at the specified offset.
*
* @param input the array of bytes.
*
* @param offset the offset to start from in the array of bytes.
*
* @param len the number of bytes to use, starting at
* <code>offset</code>.
*/
public void update(byte[] input, int offset, int len) {
if (input == null) {
throw new IllegalArgumentException("No input buffer given");
}
if (input.length - offset < len) {
throw new IllegalArgumentException("Input buffer too short");
}
engineUpdate(input, offset, len);
state = IN_PROGRESS;
}
/**
* Updates the digest using the specified array of bytes.
*
* @param input the array of bytes.
*/
public void update(byte[] input) {
engineUpdate(input, 0, input.length);
state = IN_PROGRESS;
}
/**
* Update the digest using the specified ByteBuffer. The digest is
* updated using the <code>input.remaining()</code> bytes starting
* at <code>input.position()</code>.
* Upon return, the buffer's position will be equal to its limit;
* its limit will not have changed.
*
* @param input the ByteBuffer
* @since 1.5
*/
public final void update(ByteBuffer input) {
if (input == null) {
throw new NullPointerException();
}
engineUpdate(input);
state = IN_PROGRESS;
}
/**
* Completes the hash computation by performing final operations
* such as padding. The digest is reset after this call is made.
*
* @return the array of bytes for the resulting hash value.
*/
public byte[] digest() {
/* Resetting is the responsibility of implementors. */
byte[] result = engineDigest();
state = INITIAL;
return result;
}
/**
* Completes the hash computation by performing final operations
* such as padding. The digest is reset after this call is made.
*
* @param buf output buffer for the computed digest
*
* @param offset offset into the output buffer to begin storing the digest
*
* @param len number of bytes within buf allotted for the digest
*
* @return the number of bytes placed into <code>buf</code>
*
* @exception DigestException if an error occurs.
*/
public int digest(byte[] buf, int offset, int len) throws DigestException {
if (buf == null) {
throw new IllegalArgumentException("No output buffer given");
}
if (buf.length - offset < len) {
throw new IllegalArgumentException
("Output buffer too small for specified offset and length");
}
int numBytes = engineDigest(buf, offset, len);
state = INITIAL;
return numBytes;
}
/**
* Performs a final update on the digest using the specified array
* of bytes, then completes the digest computation. That is, this
* method first calls {@link #update(byte[]) update(input)},
* passing the <i>input</i> array to the <code>update</code> method,
* then calls {@link #digest() digest()}.
*
* @param input the input to be updated before the digest is
* completed.
*
* @return the array of bytes for the resulting hash value.
*/
public byte[] digest(byte[] input) {
update(input);
return digest();
}
/**
* Returns a string representation of this message digest object.
*/
public String toString() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream p = new PrintStream(baos);
p.print(algorithm+" Message Digest from "+provider.getName()+", ");
switch (state) {
case INITIAL:
p.print("<initialized>");
break;
case IN_PROGRESS:
p.print("<in progress>");
break;
}
p.println();
return (baos.toString());
}
/**
* Compares two digests for equality. Does a simple byte compare.
*
* @param digesta one of the digests to compare.
*
* @param digestb the other digest to compare.
*
* @return true if the digests are equal, false otherwise.
*/
public static boolean isEqual(byte digesta[], byte digestb[]) {
if (digesta.length != digestb.length)
return false;
for (int i = 0; i < digesta.length; i++) {
if (digesta[i] != digestb[i]) {
return false;
}
}
return true;
}
/**
* Resets the digest for further use.
*/
public void reset() {
engineReset();
state = INITIAL;
}
/**
* Returns a string that identifies the algorithm, independent of
* implementation details. The name should be a standard
* Java Security name (such as "SHA", "MD5", and so on).
* See Appendix A in the <a href=
* "../../../technotes/guides/security/crypto/CryptoSpec.html#AppA">
* Java Cryptography Architecture API Specification & Reference </a>
* for information about standard algorithm names.
*
* @return the name of the algorithm
*/
public final String getAlgorithm() {
return this.algorithm;
}
/**
* Returns the length of the digest in bytes, or 0 if this operation is
* not supported by the provider and the implementation is not cloneable.
*
* @return the digest length in bytes, or 0 if this operation is not
* supported by the provider and the implementation is not cloneable.
*
* @since 1.2
*/
public final int getDigestLength() {
int digestLen = engineGetDigestLength();
if (digestLen == 0) {
try {
MessageDigest md = (MessageDigest)clone();
byte[] digest = md.digest();
return digest.length;
} catch (CloneNotSupportedException e) {
return digestLen;
}
}
return digestLen;
}
/**
* Returns a clone if the implementation is cloneable.
*
* @return a clone if the implementation is cloneable.
*
* @exception CloneNotSupportedException if this is called on an
* implementation that does not support <code>Cloneable</code>.
*/
public Object clone() throws CloneNotSupportedException {
if (this instanceof Cloneable) {
return super.clone();
} else {
throw new CloneNotSupportedException();
}
}
/*
* The following class allows providers to extend from MessageDigestSpi
* rather than from MessageDigest. It represents a MessageDigest with an
* encapsulated, provider-supplied SPI object (of type MessageDigestSpi).
* If the provider implementation is an instance of MessageDigestSpi,
* the getInstance() methods above return an instance of this class, with
* the SPI object encapsulated.
*
* Note: All SPI methods from the original MessageDigest class have been
* moved up the hierarchy into a new class (MessageDigestSpi), which has
* been interposed in the hierarchy between the API (MessageDigest)
* and its original parent (Object).
*/
static class Delegate extends MessageDigest {
// The provider implementation (delegate)
private MessageDigestSpi digestSpi;
// constructor
public Delegate(MessageDigestSpi digestSpi, String algorithm) {
super(algorithm);
this.digestSpi = digestSpi;
}
/**
* Returns a clone if the delegate is cloneable.
*
* @return a clone if the delegate is cloneable.
*
* @exception CloneNotSupportedException if this is called on a
* delegate that does not support <code>Cloneable</code>.
*/
public Object clone() throws CloneNotSupportedException {
if (digestSpi instanceof Cloneable) {
MessageDigestSpi digestSpiClone =
(MessageDigestSpi)digestSpi.clone();
// Because 'algorithm', 'provider', and 'state' are private
// members of our supertype, we must perform a cast to
// access them.
MessageDigest that =
new Delegate(digestSpiClone,
((MessageDigest)this).algorithm);
that.provider = ((MessageDigest)this).provider;
that.state = ((MessageDigest)this).state;
return that;
} else {
throw new CloneNotSupportedException();
}
}
protected int engineGetDigestLength() {
return digestSpi.engineGetDigestLength();
}
protected void engineUpdate(byte input) {
digestSpi.engineUpdate(input);
}
protected void engineUpdate(byte[] input, int offset, int len) {
digestSpi.engineUpdate(input, offset, len);
}
protected void engineUpdate(ByteBuffer input) {
digestSpi.engineUpdate(input);
}
protected byte[] engineDigest() {
return digestSpi.engineDigest();
}
protected int engineDigest(byte[] buf, int offset, int len)
throws DigestException {
return digestSpi.engineDigest(buf, offset, len);
}
protected void engineReset() {
digestSpi.engineReset();
}
}
}
if (digesta[i] != digestb[i])
is the issue it’s a non time constant operation path looks like this
--- a/src/share/classes/java/security/MessageDigest.java
+++ b/src/share/classes/java/security/MessageDigest.java
@@ -1,5 +1,5 @@
/*
+ * Copyright 1996-2009 Sun Microsystems, Inc. All Rights Reserved.
- * Copyright 1996-2006 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -414,17 +414,16 @@ public abstract class MessageDigest extends MessageDigestSpi {
*
* @return true if the digests are equal, false otherwise.
*/
+ public static boolean isEqual(byte[] digesta, byte[] digestb) {
+ if (digesta.length != digestb.length) {
- public static boolean isEqual(byte digesta[], byte digestb[]) {
- if (digesta.length != digestb.length)
return false;
+ }
+ int result = 0;
+ // time-constant comparison
for (int i = 0; i < digesta.length; i++) {
+ result |= digesta[i] ^ digestb[i];
- if (digesta[i] != digestb[i]) {
- return false;
- }
}
+ return result == 0;
- return true;
}
/**
CVE-2022-2X24X
src/main/java/io/github/javaezlib/javaez/extensions/Security.java
package io.github.javaezlib.javaez.extensions;
import io.github.javaezlib.javaez.backend.ErrorSystem;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Base64;
/**
* The JavaEZ Security extension. Allows different security-related functions.
* @since 1.6
*/
@SuppressWarnings("deprecation")
public class Security {
/**
* Locks a piece of text with a password.
* (For technical people: This function encrypts the data in the text using AES-256-CBC with a PBKDF2-based cipher generated from the password)
* @param text The text to lock
* @param password The password to use
* @return The locked text
* @since 1.6
*/
public static String lockText(String text, String password) {
try {
byte[] salt = genSaltFromPassword(password);
PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, 65536, 256);
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
SecretKey originalKey = factory.generateSecret(keySpec);
SecretKey key = new SecretKeySpec(originalKey.getEncoded(), "AES");
byte[] iv = new byte[16];
new SecureRandom().nextBytes(iv);
IvParameterSpec ivParamSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, ivParamSpec);
byte[] encrypted = cipher.doFinal(text.getBytes(StandardCharsets.UTF_8));
byte[] full = new byte[encrypted.length + iv.length];
int index = 0;
for(byte b : iv) {
full[index] = b;
index++;
}
for(byte b : encrypted) {
full[index] = b;
index++;
}
return Base64.getEncoder().encodeToString(full);
} catch(Exception ex) {
ErrorSystem.handleError("Could not lock text.");
return null;
}
}
/**
* Unlocks some text that was locked using {@link #lockText(String, String)}.
* (For technical people: This function decrypts the data in the text using AES-256-CBC with a PBKDF2-based cipher generated from the password)
* @param text The locked text to unlock
* @param password The password used to lock the text
* @return The unlocked text
* @since 1.6
*/
public static String unlockText(String text, String password) {
try {
byte[] salt = genSaltFromPassword(password);
PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, 65536, 256);
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
SecretKey originalKey = factory.generateSecret(keySpec);
SecretKey key = new SecretKeySpec(originalKey.getEncoded(), "AES");
byte[] encrypted = Base64.getDecoder().decode(text);
byte[] iv = Arrays.copyOfRange(encrypted, 0, 16);
byte[] encData = Arrays.copyOfRange(encrypted, 16, encrypted.length);
IvParameterSpec ivParamSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, ivParamSpec);
byte[] decrypted = cipher.doFinal(encData);
return new String(decrypted, StandardCharsets.UTF_8);
} catch(Exception ex) {
ErrorSystem.handleError("Could not unlock text.");
return null;
}
}
/**
* An internal method used for generated PBKDF2 salts
* @param password The password to generate the salt with
* @return The salt
* @since 1.6
*/
private static byte[] genSaltFromPassword(String password) {
StringBuilder sb = new StringBuilder();
sb.append(password);
sb.reverse();
String reversed = sb.toString();
return reversed.getBytes(StandardCharsets.UTF_8);
}
}
using Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
this can make encryption vulnerable. so in Diff they used AES/GCM/NoPadding
--- a/src/main/java/io/github/javaezlib/javaez/extensions/Security.java
+++ b/src/main/java/io/github/javaezlib/javaez/extensions/Security.java
@@ -5,6 +5,7 @@ import io.github.javaezlib.javaez.backend.ErrorSystem;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
+import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
@@ -22,7 +23,7 @@ public class Security {
/**
* Locks a piece of text with a password.
- * (For technical people: This function encrypts the data in the text using AES-256-CBC with a PBKDF2-based cipher generated from the password)
+ * (For technical people: This function encrypts the data in the text using AES-256-GCM with a PBKDF2-based cipher generated from the password)
* @param text The text to lock
* @param password The password to use
* @return The locked text
@@ -37,9 +38,9 @@ public class Security {
SecretKey key = new SecretKeySpec(originalKey.getEncoded(), "AES");
byte[] iv = new byte[16];
new SecureRandom().nextBytes(iv);
- IvParameterSpec ivParamSpec = new IvParameterSpec(iv);
- Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
- cipher.init(Cipher.ENCRYPT_MODE, key, ivParamSpec);
+ GCMParameterSpec gcmParamSpec = new GCMParameterSpec(128, iv);
+ Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
+ cipher.init(Cipher.ENCRYPT_MODE, key, gcmParamSpec);
byte[] encrypted = cipher.doFinal(text.getBytes(StandardCharsets.UTF_8));
byte[] full = new byte[encrypted.length + iv.length];
int index = 0;
@@ -54,13 +55,14 @@ public class Security {
return Base64.getEncoder().encodeToString(full);
} catch(Exception ex) {
ErrorSystem.handleError("Could not lock text.");
+ ex.printStackTrace();
return null;
}
}
/**
* Unlocks some text that was locked using {@link #lockText(String, String)}.
- * (For technical people: This function decrypts the data in the text using AES-256-CBC with a PBKDF2-based cipher generated from the password)
+ * (For technical people: This function decrypts the data in the text using AES-256-GCM with a PBKDF2-based cipher generated from the password)
* @param text The locked text to unlock
* @param password The password used to lock the text
* @return The unlocked text
@@ -76,9 +78,9 @@ public class Security {
byte[] encrypted = Base64.getDecoder().decode(text);
byte[] iv = Arrays.copyOfRange(encrypted, 0, 16);
byte[] encData = Arrays.copyOfRange(encrypted, 16, encrypted.length);
- IvParameterSpec ivParamSpec = new IvParameterSpec(iv);
- Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
- cipher.init(Cipher.DECRYPT_MODE, key, ivParamSpec);
+ GCMParameterSpec gcmParamSpec = new GCMParameterSpec(128, iv);
+ Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
+ cipher.init(Cipher.DECRYPT_MODE, key, gcmParamSpec);
byte[] decrypted = cipher.doFinal(encData);
return new String(decrypted, StandardCharsets.UTF_8);
} catch(Exception ex) {
CVE-2022-4x3x5
streampark-console/streampark-console-service/src/main/java/org/apache/streampark/console/system/controller/UserController.java
/*
* 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.streampark.console.system.controller;
import org.apache.streampark.console.base.domain.ResponseCode;
import org.apache.streampark.console.base.domain.RestRequest;
import org.apache.streampark.console.base.domain.RestResponse;
import org.apache.streampark.console.base.util.ShaHashUtils;
import org.apache.streampark.console.core.enums.UserType;
import org.apache.streampark.console.core.service.CommonService;
import org.apache.streampark.console.system.entity.Team;
import org.apache.streampark.console.system.entity.User;
import org.apache.streampark.console.system.service.TeamService;
import org.apache.streampark.console.system.service.UserService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.List;
import java.util.Map;
@Slf4j
@Validated
@RestController
@RequestMapping("user")
public class UserController {
@Autowired
private UserService userService;
@Autowired
private TeamService teamService;
@Autowired
private CommonService commonService;
@PostMapping("detail")
public User detail(@NotBlank(message = "{required}") @PathVariable String username) {
return this.userService.findByName(username);
}
@PostMapping("list")
@RequiresPermissions(value = {"user:view", "app:view"}, logical = Logical.OR)
public RestResponse userList(RestRequest restRequest, User user) {
IPage<User> userList = userService.findUserDetail(user, restRequest);
return RestResponse.success(userList);
}
@PostMapping("post")
@RequiresPermissions("user:add")
public RestResponse addUser(@Valid User user) throws Exception {
this.userService.createUser(user);
return RestResponse.success();
}
@PutMapping("update")
@RequiresPermissions("user:update")
public RestResponse updateUser(@Valid User user) throws Exception {
this.userService.updateUser(user);
return RestResponse.success();
}
@DeleteMapping("delete")
@RequiresPermissions("user:delete")
public RestResponse deleteUser(Long userId) throws Exception {
this.userService.deleteUser(userId);
return RestResponse.success();
}
@PutMapping("profile")
public RestResponse updateProfile(@Valid User user) throws Exception {
this.userService.updateProfile(user);
return RestResponse.success();
}
@PutMapping("avatar")
public RestResponse updateAvatar(
@NotBlank(message = "{required}") String username,
@NotBlank(message = "{required}") String avatar)
throws Exception {
this.userService.updateAvatar(username, avatar);
return RestResponse.success();
}
@PostMapping("getNoTokenUser")
public RestResponse getNoTokenUser() {
List<User> userList = this.userService.getNoTokenUser();
return RestResponse.success(userList);
}
@PostMapping("check/name")
public RestResponse checkUserName(@NotBlank(message = "{required}") String username) {
boolean result = this.userService.findByName(username) == null;
return RestResponse.success(result);
}
@PostMapping("check/password")
public RestResponse checkPassword(
@NotBlank(message = "{required}") String username,
@NotBlank(message = "{required}") String password) {
User user = userService.findByName(username);
String salt = user.getSalt();
String encryptPassword = ShaHashUtils.encrypt(salt, password);
boolean result = StringUtils.equals(user.getPassword(), encryptPassword);
return RestResponse.success(result);
}
@PutMapping("password")
public RestResponse updatePassword(
@NotBlank(message = "{required}") String username,
@NotBlank(message = "{required}") String password)
throws Exception {
userService.updatePassword(username, password);
return RestResponse.success();
}
@PutMapping("password/reset")
@RequiresPermissions("user:reset")
public RestResponse resetPassword(@NotBlank(message = "{required}") String usernames)
throws Exception {
String[] usernameArr = usernames.split(StringPool.COMMA);
this.userService.resetPassword(usernameArr);
return RestResponse.success();
}
@PostMapping("types")
@RequiresPermissions("user:types")
public RestResponse userTypes() {
return RestResponse.success(UserType.values());
}
@PostMapping("initTeam")
public RestResponse initTeam(Long teamId, Long userId) {
Team team = teamService.getById(teamId);
if (team == null) {
return RestResponse.fail("teamId is invalid", ResponseCode.CODE_FAIL_ALERT);
}
userService.setLastTeam(teamId, userId);
return RestResponse.success();
}
@PostMapping("setTeam")
public RestResponse setTeam(Long teamId) {
Team team = teamService.getById(teamId);
if (team == null) {
return RestResponse.fail("teamId is invalid", ResponseCode.CODE_FAIL_ALERT);
}
User user = commonService.getCurrentUser();
//1) set the latest team
userService.setLastTeam(teamId, user.getUserId());
//2) get latest userInfo
user.dataMasking();
Map<String, Object> infoMap = userService.generateFrontendUserInfo(user, teamId, null);
return new RestResponse().data(infoMap);
}
@PostMapping("appOwners")
public RestResponse appOwners(Long teamId) {
List<User> userList = userService.findByAppOwner(teamId);
userList.forEach(User::dataMasking);
return RestResponse.success(userList);
}
}
streampark-console/streampark-console-service/src/main/java/org/apache/streampark/console/system/service/impl/UserServiceImpl.java
/*
* 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.streampark.console.system.service.impl;
import org.apache.streampark.common.util.AssertUtils;
import org.apache.streampark.console.base.domain.RestRequest;
import org.apache.streampark.console.base.exception.ApiAlertException;
import org.apache.streampark.console.base.util.ShaHashUtils;
import org.apache.streampark.console.system.authentication.JWTToken;
import org.apache.streampark.console.system.entity.Team;
import org.apache.streampark.console.system.entity.User;
import org.apache.streampark.console.system.mapper.UserMapper;
import org.apache.streampark.console.system.service.MemberService;
import org.apache.streampark.console.system.service.MenuService;
import org.apache.streampark.console.system.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Nullable;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
@Slf4j
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
@Autowired
private MemberService memberService;
@Autowired
private MenuService menuService;
@Override
public User findByName(String username) {
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<User>()
.eq(User::getUsername, username);
return baseMapper.selectOne(queryWrapper);
}
@Override
public IPage<User> findUserDetail(User user, RestRequest request) {
Page<User> page = new Page<>();
page.setCurrent(request.getPageNum());
page.setSize(request.getPageSize());
IPage<User> resPage = this.baseMapper.findUserDetail(page, user);
AssertUtils.state(resPage != null);
if (resPage.getTotal() == 0) {
resPage.setRecords(Collections.emptyList());
}
return resPage;
}
@Override
@Transactional(rollbackFor = Exception.class)
public void updateLoginTime(String username) {
User user = new User();
user.setLastLoginTime(new Date());
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<User>()
.eq(User::getUsername, username);
this.baseMapper.update(user, queryWrapper);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void createUser(User user) {
user.setCreateTime(new Date());
user.setAvatar(User.DEFAULT_AVATAR);
String salt = ShaHashUtils.getRandomSalt();
String password = ShaHashUtils.encrypt(salt, user.getPassword());
user.setSalt(salt);
user.setPassword(password);
save(user);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void updateUser(User user) {
user.setPassword(null);
user.setModifyTime(new Date());
updateById(user);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteUser(Long userId) {
removeById(userId);
this.memberService.deleteByUserId(userId);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void updateProfile(User user) {
updateById(user);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void updateAvatar(String username, String avatar) {
User user = new User();
user.setAvatar(avatar);
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<User>()
.eq(User::getUsername, username);
this.baseMapper.update(user, queryWrapper);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void updatePassword(String username, String password) {
User user = new User();
String salt = ShaHashUtils.getRandomSalt();
password = ShaHashUtils.encrypt(salt, password);
user.setSalt(salt);
user.setPassword(password);
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<User>()
.eq(User::getUsername, username);
this.baseMapper.update(user, queryWrapper);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void resetPassword(String[] usernames) {
for (String username : usernames) {
User user = new User();
String salt = ShaHashUtils.getRandomSalt();
String password = ShaHashUtils.encrypt(salt, User.DEFAULT_PASSWORD);
user.setSalt(salt);
user.setPassword(password);
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<User>()
.eq(User::getUsername, username);
this.baseMapper.update(user, queryWrapper);
}
}
@Override
public Set<String> getPermissions(Long userId, @Nullable Long teamId) {
List<String> userPermissions = this.menuService.findUserPermissions(userId, teamId);
return new HashSet<>(userPermissions);
}
@Override
public List<User> getNoTokenUser() {
List<User> users = this.baseMapper.getNoTokenUser();
if (!users.isEmpty()) {
users.forEach(User::dataMasking);
}
return users;
}
@Override
public void setLastTeam(Long teamId, Long userId) {
User user = getById(userId);
AssertUtils.checkArgument(user != null);
user.setLastTeamId(teamId);
this.baseMapper.updateById(user);
}
@Override
public void clearLastTeam(Long userId, Long teamId) {
User user = getById(userId);
AssertUtils.checkArgument(user != null);
if (!teamId.equals(user.getLastTeamId())) {
return;
}
this.baseMapper.clearLastTeamByUserId(userId);
}
@Override
public void clearLastTeam(Long teamId) {
this.baseMapper.clearLastTeamByTeamId(teamId);
}
@Override
public void fillInTeam(User user) {
if (user.getLastTeamId() == null) {
List<Team> teams = memberService.findUserTeams(user.getUserId());
if (CollectionUtils.isEmpty(teams)) {
throw new ApiAlertException("The current user not belong to any team, please contact the administrator!");
} else if (teams.size() == 1) {
Team team = teams.get(0);
user.setLastTeamId(team.getId());
this.baseMapper.updateById(user);
}
}
}
@Override
public List<User> findByAppOwner(Long teamId) {
return baseMapper.findByAppOwner(teamId);
}
/**
* generate user info, contains: 1.token, 2.vue router, 3.role, 4.permission, 5.personalized config info of frontend
*
* @param user user
* @return UserInfo
*/
@Override
public Map<String, Object> generateFrontendUserInfo(User user, Long teamId, JWTToken token) {
AssertUtils.checkNotNull(user);
Map<String, Object> userInfo = new HashMap<>(8);
// 1) token & expire
if (token != null) {
userInfo.put("token", token.getToken());
userInfo.put("expire", token.getExpireAt());
}
// 2) user
user.dataMasking();
userInfo.put("user", user);
// 3) permissions
Set<String> permissions = this.getPermissions(user.getUserId(), teamId);
userInfo.put("permissions", permissions);
return userInfo;
}
}